Lesson 2: Development environment IDLE

Purpose: To use the environment IDLE
Contents: Functions input and print.
Data type bool.
if-, while- and for-statements.
Work procedure: You are encouraged to discuss the work with others but should write your own code.
Estimated working time: 3 hours.
Examination: No mandatory examination. If you are having trouble understanding parts of the material or have other questions, feel free to grab a teaching assistant and ask them.

Using IDLE

So far we've been running Python in a commando window, in which we've written separate commandos that were immediately executed. However, normally all these commandos (or rather, Python statements, lines of code) are gathered in a file which can then be edited, save and run multiple times. It is possible to use any kind of text editor to write such a file, but it's recommended that you use one which supports Python-code.

Included with the Python installation is a development environment called IDLE, which (among other things) contains a text editor.

IDLE

You can start IDLE either by writing idle or idle3 in a commando window or by clicking the IDLE icon in the Python 3 map that is created when installing Python:

(The pictures in this document are from a Macintosh - this process may look slightly different for other system.)

IDLE

When IDLE is started it opens its own commando window. Here you can write Python statements that are subsequently executed exactly as was done previously.

IDLE

To open a new window, click File and choose NewFile from the dropdown.

IDLE

This will look something like this:

In the window titled "untitled" you can now write Python statements. These statements will be executed first when the file is "run" using a special commando.

The print-statement

When we write our statements directly into the commando window the answers too are written directly there. This is not the case when the statements in a file are executed. Instead a print-function much be used to see the results of the statements.

Write (or copy and paste) the following lines into the untitled window:

print('Welcome to the Python world')
print('Programming is fun!', '!'*10)

Before we can run the program we have to save it. This is done via Save in the dropdown menu for File:

IDLE

Name the file ex1.py.

Run the program via Run Module in the dropdown menu for Run!

Note that we now have to use the print function to see any results.

Reading data through input

Instead of assigning values to variables in the code, the program can ask the user what the values should be.

Example:

name = input('What is your name?')
print(f'Welcome {name}!')

Add these two lines to the file, save, and test run!

The function input prints the given text (the "argument"), in this case "What's your name?", as a guide to the user. The program then waits for the user to write something (and press enter). Whatever the user wrote is then placed as a value for the name variable.

Note that input always returns the answer as a string, even if what the user has written may be seen as a number. So if we want to use the answer in a calculation we need to convert it to an int or a float.

Example:

In the US cars' fuel consumption are given in miles per gallon rather than liter per mile. The following code helps convert between these two (1 mile = 1609m, 1 US gallon = 3.785 l):

mpg = float(input('Input miles per gallon: '))
lpm = 10./(mpg*1.609/3.785)
print(f'This corresponds to {lpm} liter per mil')

Test run this!

The answer contains a lot of bothersome numbers. The function round can be used for rounding to a suitable amount of decimals. Add the line lpm = round(lpm, 2) before the print statement in order to round the answer down to 2 decimals.

Exercises

  1. Write and test run a program that takes in a temperature value in Fahrenheit and prints the equivalent temperature in Celsius, with 1 decimal. Conversion formula can be found here. Answer
    f = float(input("Degrees in Fahrenheit: "))
    c = round((f-32)/1.8, 1)
    print('is equivalent to', c, 'degrees in Celsius')
    
  2. Write and test run a program that takes in a principal sum (in SEK, integer), an interest rate (in percent, float number), and a number of years (integer), and then calculates and prints out what the principal sum is with the given interest rate after the given number of years. Answer
    k = int(input('Principal sum: '))
    r = float(input('Interest rate: '))
    n = int(input('Years: '))
    result = k*(1+r/100)**n
    print('The new amount is: ', round(result))  
    
  3. Write and test run a program that takes in two float numbers p and q, and prints the roots to the quadratic equation x2 + px + q = 0
    Test the solution using p = -3 and q = 2, p = q = -1, and p = q = 1.
    Answer
    import math
    p = float(input('p: '))
    q = float(input('q: '))
    disc = p*p - 4*q
    d = math.sqrt(disc)
    print('x1 = ', (-p + d) /2.0)
    print('x2 = ', (-p - d) /2.0)
    

The if statement

So far all statements have been performed sequentially, one after the other. It is however common in programming to want to choose different roads depending on some condition. To do this we need to use a so called if statement.

Example: Take in two numbers and print the largest.

x = float(input('Input the first number: '))
y = float(input('Input the second number: '))
if x > y:
    print('The first number is the largest')
    print('This is also printed if the first number is the largest')
else:
    print('Either the second number is the largest')
    print('or the numbers are of equal size')
print('Now we know something of the relation between the numbers')

Copy and test run!

Note:

Both these points are essential for the if statement's function!

If the condition is true, that is if x is larger than y, the indented statements up until else: (two statements, in this case) are executed. If the condition is false, that is if x is smaller than or equal to y, the indented statements after else: are executed.

Exercise

  1. Modify the program that solved the quadratic equation so that it prints the roots if they are real, or the line 'Complex roots' if not. Answer
      import math
      p = float(input('p: '))
      q = float(input('q: '))
      disc = p*p - 4*q
      if disc < 0:
          print('Complex roots')
      else:
          d = math.sqrt(disc)
          print('x1 = ', (-p + d) /2.0)
          print('x2 = ', (-p - d) /2.0)
    

The statement elif

The branches (statements following the rows with colons) can contain any arbitrary statements, for example if statements.

Example: Assume that we want to investigate whether a number is larger than, equal to or smaller than 0.

if x > 0:
    print('Positive case')
    ...more statements
else:
    if x == 0:
        print('Case 0')
        ...more statements
    else:
        print('Negative case')
        ...more statements
print('After all cases')

This can more clearly be expressed using elif, which can be read as "else if":

if x > 0:
    print('Positive case')
    ...more statements
elif x == 0:
    print('Case 0')
    ...more statements
else:
    print('Negative case')
    ...more statements
print('After all cases')

Logical expressions

A logical expression is an expression that can be either true or false. In Python this data type is called bool and the two possible values are written as True and False.

The conditions in the if statements above are examples of logical expressions. These are constructed using relational operators > and ==.

OperatorMeaning
==equal to
!=not equal to
<less than
<=less than or equal to
>greater than
>=greater than or equal to

The operands must be comparable, e.g. both are numbers or both are strings.

Python also has the logical operators and, or, and not.

Example: The statement

 teenager = age>12 and age<20

sets the variable teenager to True if the variable age is greater than 12 but less than 20.

(Side note: In Python a shorter formulation can be used:

 teenager = 12 < age < 20)

Additional example: The code

if day=="Saturday" or day=="Sunday":
    print("Weekend")
else:
    print("Workday")

The while statement

Another frequent situation we encounter when programming is that we want to repeat a series of statements multiple times — in a so called loop.

Example: The following program calculates n! = 1·2·3· ... ·n for a given value n.

print('Calculation of n!')
n = int(input('Input n: '))     # input returns a string
prod = 1
i = 1
while i <= n:
    prod *= i
    i += 1
print(f'{n}! = {prod}')

As long as the condition after while is true, i.e. as long as i is less than or equal to n, the indented statements are repeated. The variable prod accumulates the product and the variable i counts the quantity.

Both colon and indentation are essential here, just as with the if statement!

Example: Read a number and add it to a list.

Ask the user to enter some positive numbers and add them to a list. Stop when 0 is given as input.

numbers = []   # An empty list
print('Enter positive numbers. Quit with 0')
x = int(input('First: '))	
while x > 0:
    numbers.append(x)
    x = int(input('Next: '))
print('Entered list: ', numbers)

The break statement

Normally a while loop is ended when the condition turns false, but it is also possible to exit the loop using a so called break statement.

Example: Guess what number the computer is thinking of

import random                   # package with randomizing functions 

number = random.randint(1,100)  # Random number between 1 and 100 
while True:                     # "Infinite loop"
    ans = int(input('Guess: '))
    if ans < number:
        print('Too small!')
    elif ans > number:
        print('Too big!')
    else:
        print('Correct!')
        break                   # Exit the loop
print("That's all for this time")

Note: Always try to write the code so that it's clear from the while condition when the loop is exited (this is always possible!), use break only if it makes the code substantially simpler and easier to read.

Exercises

  1. Add code to the example above so that the program counts the number of even numbers in the entered list, using a while loop. Answer
    n = 0
    i = 0
    while i < len(numbers):
        if numbers[i]%2 == 0:
            n += 1
        i += 1
    print('Number of even numbers: ', n)
    
  2. Write code that asks the user to enter a positive number. The question shall repeated as long as the entered number isn't positive, until the user does as requested. Print "OK" when the input has been successful. Answer
    x = input('Enter a positive number: ')
    while float(x) <= 0:
        x = float(input('Not positive! Try again: '))
    print('OK')
    
  3. Modify the code in the exercise so that the program prints "Finally!" if the user tried more than 3 times. Answer
    x = int(input('Enter a positive number: '))
    tries = 1
    while x <= 0:
        x = input('Not positive! Try again: ')
        tries += 1
    if tries <= 3:
        print('OK')
    else:
        print('Finally!')
    
  4. Rewrite the code in the guessing game so that it doesn't use break! Answer
    import random
    
    number = random.randint(1,100)
    
    ans = input('Guess: ')
    while ans != number:
        if ans < number:
            print('Too small')
        else:
            print('Too big!')
        ans = input('Guess: ')
    print('Correct!')
    print('That's all for this time')
    

The for statement

Another way to repeat code is to use the for statement. The code for many of the examples and exercise above is actually simpler when using this statement rather than while.

Example: Calculating n! = 1·2·3· ... ·n

     with for:       with while:
prod = 1
for i in range(1, n+1):
    prod *= i
        
prod = 1 i = 1 while i <= n: prod *= i i += 1

The expression range(1, n+1) will successively give the values 1, 2, ..., n to the variable i. Consequently we no longer need to increase i and keep an eye on when the iteration should end. Note that the last value (n+1) never is assigned to i.

prod = 1
for i in range(n):
    prod *= (i + 1)

The call range(n) will go through the numbers 0, 1, ..., n-1. The calculation above can therefore be made by the following code:

The for statement can be used to go through values in a list:

for variable in list:
The variable will successively take on the different values in the list.

Example: To go through the list numbers to count the number of even numbers the for statement looks as follows (version with while to the right):

n = 0
for x in numbers:
    if x%2 == 0:
        n += 1
     
n = 0
i = 0
while i < len(numbers):
    if numbers[i]%2 == 0:
        n += 1
    i += 1

Exercises

  1. Write a piece of code that reads a number x and an integer n, and calculates xn with multiplications, i.e. without using the operator ** or the function pow. Note that n can be negative! Answer
    x = float(input('Enter a number: '))
    n = int(input('Enter an integer: ')
    p = 1
    for i in range(0, abs(n)):
        p *= x
    if n < 0:
        p = 1/p
    print(f'{x}^{n} = {p}')
    
  2. Write a piece of code that creates a list containing the squared numbers of another list. Answer
    numbers = [2, 4, 1, 9, 7]
    squares = []
    for x in numbers:
        quares.append(x*x)
    print(numbers)
    print(squares)
    

Nestled for statements

A loop body in a for (or while) statement can contain any other statements, including new for statements.

Example: Assume that we have a list with first names and a list with surnames, and that we want to generate a new list with all possible combinations of first names and surnames. The program

firstnames = ['Bo', 'Eva', 'Ola']
surnames = ['Ek', 'Strand']

result = []
for fn in firstnames:
    for sn in surnames:
        result.append(fn + ' ' + sn)
print(result)
gives the printout
['Bo Ek', 'Bo Strand', 'Eva Ek', 'Eva Strand', 'Ola Ek', 'Ola Strand']

For every possible first name (fn the code will go through every possible surname (sn), and add the combination to the result variable.

Exercise

  1. Given a list of positive integers, e.g. [10, 15, 24, 17, 9, 8, 3]. Write a piece of code that prints out a horizontal bar chart where every bar contains as many * symbols as the value in the list indicates. In the given case the printout should be:
    ********** *************** ************************ ***************** ********* ******** ***
    Hint: The call print('*', end='') suppresses the line-break, i.e. next print will continue on the same line. Answer
      values = [10, 15, 24, 17, 9, 8, 3]
      for v in values:
          for i in range(v):
              print('*', end='')
          print()		# New line
    

    Side note: This result can be achieved more easily with list operators. We'll come back to this later in the course.

Comments and code layout

Program code is read not only by computers but also by humans. To make the code easier to read it's advisable to write comments, i.e. text that's there only for the human eye and is ignored by the computer.

The # symbol is used in Python to mark that the rest of the line is a comment. An example can be seen in the next section. We'll go through some rules and principles for commenting later on.

In Python the code layout isn't just for humans, it effects the way the code is interpreted by the computer as well. The indentation, used in if and while statements above, are examples of this!

Regulations for this course can be found in the document PEP 8 -- Style Guide for Python Code

The most important points are:

Count on that the teaching assistants will refuse to look at code that doesn't fulfill these basic criteria!


Go to next lesson or go back

Valid CSS!