Python Stuff

Tutorial, Part 3: Logicals, if blocks, and while loops

Contact: Paul Kushner, paul.kushner@utoronto.ca

Computer programs take actions based on conditions and execute sequences of commands repetitively using loops. Decision branches --- different paths followed by a program depending on conditions --- are determined by logical tests. There are many possible logical tests; for example, whether one number is greater than, equal to, or less than a number, whether two character strings are the same, and so on.

In this part of the tutorial, we will introduce logical statements, logical variables and if statements. We will then introduce while loops, which are controlled by logical conditions.

1. Review

Before learning about logicals, if blocks, and while loops, let's review where we stand. We know the basic operation involved in calculations, whether they are used in complex equations or simple operations. We know how to retrieve user input and use it in our own code. Finally, we also learned in the last section how to make our own functions to reduce the amount of code that we need to write (this was optional for Year 1 students). If we add all of this knowledge together we can accomplish a broad range of tasks using Python. Try the following activity below which reviews how to define functions:

Review Exercise: Activity 0 (Optional for Year 1 students)
Let's first define a function that takes no parameters and adds two user entered numbers together three times. Enter the following in a new window and save it.

 def triple_sum():
    num_1 = input('Please enter the first number. ')
    num_2 = input('Please enter the second number. ')
    temp1 = num_1*3
    temp2 = num_2*3
    final = temp1 + temp2
    print final

Note, this is by far not the best way to add two numbers three times, it could in fact be done in only one line. Now we can call this function over and over in the python shell. Click Run --> Run Module or hit F5. If you had the shell open you should have noticed it change. If you did not have the shell open, open it now by clicking Run --> Python Shell. Now in the shell type

IDLE 1.2.4
>>> ================================ RESTART ================================
>>>
>>>triple_sum()

Just a reminder, this is called calling the function. Once this is done your created prompt should appear asking you to input the first number. Once your function has finished running, call it again to see that it will still work. Then call it again and again. The function will always be available for you to call as long as you don't restart your shell.

2. Logicals and logical variables

Programming languages are great for deciding actions based on conditions and for carrying out repetitive actions. Decision branches --- different paths followed by a program depending on conditions --- are determined by logical tests.

For example, 2 is less than 3, so typing

>>> 2 < 3

will result in the answer True:

>>> 2 < 3
True

but asking if 2 is greater than 3 results in "False":

>>> 2 > 3
False

(as you can verify now in a Python shell).

True and False are Boolean values and a variable that takes one of these values is called a Boolean variable or simply a Boolean for short.
[Looking in depth a bit, you should know that the Booleans True and False have numerical equivalents. False is an integer with value 0 and True is an integer with a non-zero value, but is typically taken to be 1. These numerical equivalents will often appear in Python programs, for example in the VPython examples that come with the package.]

To test equality, Python uses the double equals sign, ==, so

>>> 1 == 1
True

but

>>> 1 == 0
False

The comparison operators which you will need to use are <, >, ==, !=, >= and <=. It should be self explanatory what these do (except !=), but respectively they mean less than, greater than, equal to, not equal to, greater than or equal to and less than or equal to.

There is a way to string together conditions. For example:

>>> 1 == 1 and 1 < 2
True
>>> 1 == 1 and 1 > 2
False
>>> 1 == 1 or 1 > 2
True
>>> 1 != 1 or 1 > 2
False
>>> not 1 == 1
False

The rules are:

  • a and b evaluates to True if and only if a is True and b is True
  • a or b evaluates to False if and only if a is False and b is False
  • not a evaluates to True if and only if a is False


The operators and, or and not used in these logical tests are called Boolean operators.

Activity 1: Now do the following:

  • Predict the outcome of the following
    >>> 2 == 3
    >>> "apple" == "orange" 
    >>> from numpy import pi; pi < 3.14
  • In the second line, "apple" and "orange" are strings, which will only be equal if every character in the string is equal.
  • In the last line, we have introduced a new trick: you can separate Python commands by semicolons on the same line. So the last line actually includes two commands, one getting the value of pi from numpy, the other comparing pi to another number.
  • To complete this activity, type the statements above in a Python Shell session.



Variables can be assigned values of True and False. So, for example, we can assign the result of an equality test to a variable:

>>> a = 2; b = 3
>>> a_is_two = (a==2) #check if a is 2
>>> print a_is_two #print result
True
>>> b_is_two = (b==2) #check if b is 2
>>> print b_is_two #print result
False
 

Activity 2: Do the following

  • Predict the outcome of the following, and try them in the Python shell.
    >>> a = 2; b = 3
    >>> a_is_even = (a%2==0)
    >>> b_is_even = (b%2==0)
    >>> print "a is even:", a_is_even
    >>> print "b is even:", b_is_even

 

3. If statements and if blocks.


Logical statements are used to determine whether an action or event should take place. The standard logical statement in Python is the if statement. For example

if 2 < 3: print "hello"

(You can try typing this in IDLE at the prompt. Press return TWICE to see the outcome.)
In this fragment, the condition 2<3 is evaluated to True, and the computer carries out the action print "hello". On the other hand, the statement

if 2 > 3: print "goodbye"

would result in no output. (Again, remember to press return twice if you use this example interactively.)

A more standard format for conditional execution is the if block or the if-elif-else block. We will illustrate the if block by means of the following example:

Activity 3: To practice using logical statements, consider the following code segment, which illustrates a simple if block.

my_integer = input('Please enter your favourite integer')
if my_integer % 2 == 0:
    print "Your favourite integer is", my_integer
    print "This number is even."

To use this code

  • Open a new file in IDLE.
  • Copy and paste this code block into the file, and save it to a name and location of your choice.
  • Run the command with F5, entering an even or an odd number, as you wish. You will notice that you only get a message when an even number is inputted.


Besides the use of a logical test, this example showed a very distinctive feature of Python: the lines under the if line that ends with the colon are indented, that is, they are offset from the left margin by a few spaces. We first encountered this kind of indentation with the def statement in Part 2, Section 3 (which is optional for Year 1 physics). To repeat some of the points made there:

  • The number of spaces from the left margin is up to you, but the indentation must be consistent from line to line.
  • The indented lines are known as a code block. Python uses indented whitespace (blank spaces or tabs) to indicate code blocks.
  • The IDLE editor and shell will try to help you with indentation of code blocks code as you create scripts. Try to watch carefully what it does.


All lines in if blocks are executed only if the condition in the header line holds true. Otherwise, they are skipped. In the case of this example, the following happened:

  • You were asked to enter an integer, which you dutifully did.
  • The remainder after division of your integer by two is found and compared to zero.
  • If the remainder is equal to zero, then the next two print statements are executed. If the remainder is not equal to zero, the next two statements are skipped.


Indentation again: Let us repeat this important point about indentation. Python insists that all lines in an indented block line up: they must be indented by the same amount of white space, whether by tabs or spaces, as determined by the first indented line. Thus, Python enforces code readability by enforcing consistent alignment of code. Notice the lack of a statement to close the block, such as endif, as found in other programming languages.

The following simple extension of the previous example illustrates the use of if with else, which provides an alternate action if the if condition is not met.

my_integer = input('Please enter your favourite integer ')
print "Your favourite integer is", my_integer, "."
if my_integer%2==0:
    print "This number is even."
else:
    print "This number is odd."


Activity 4: Copy the previous code fragment into a script and run it a few times.


4. While loops

Suppose you want the computer to repeat the same action or calculation many times. To do this, you use loops. In a while loop, a set of commands is executed as long as ("while") a certain condition holds. A while loop has the following structure:

while condition:
    <line 1>
    <line 2>
    . . .
    <last line>
 

The header line is the keyword while followed by a logical condition and a colon :. Below this is an indented code block that is executed repeatedly as long as condition evaluates to True.

Activity 5: The following program illustrates the while loop and might be useful for the Canadian Space Agency (www.asc-csa.gc.ca) to assist with countdown procedures. Do the following:

  • Copy and paste the following code into a new file.
  • Save and run the script.
  • Once you've seen the script run, read the comments to understand what it's doing.
  • You can use this program as a template for any while blocks you might want to create.
    #Countdown 
    current_count = 10 
    #Exectute the lines within the while block as long as current_count is greater than zero. 
    while current_count > 0: 
         #Begin the while block. Notice that the commands are aligned with whitespace to the left. 
         print current_count 
         #reduce the current count by one 
         current_count -= 1 
     
    #All done with the while block. Print out a final message. 
    print "Blastoff!/Mise à feu"

The next program illustrates the use of a while condition, the use of an if block, and nested indentation. The object of the program, adopted from the "Byte of Python" tutorial (www.swaroopch.com), is to guess the integer given by "number" at the top of the program.

Activity 6: Before delving into the program, do the following:

  • Cut and paste the code fragment into a new Python file.
  • Run the program.
  • Then, read the comments to learn what the code does.
  • You can use this program as a template for nested "while" plus "if/elif/else" blocks.
    #Adopted from "A Byte of Python" 
    #This is the number you are going to guess. 
    number = 23 
    #This is the logical flag which tells you if you've guessed the number. 
    got_it = False 
    #This while block will only run while got_it is False. 
    #Once got-it is True, the interpreter will move to the first line after the while block. 
    while got_it == False:
        #Notice the white space to the left of this line. All the statements in the while block are aligned.
        #Enter a guess. If you accidentally enter a floating point number, int() will convert the guess to an integer.
        guess = int(input('Enter an integer : '))
        #Start an if-elif-else block. "elif" is short for "else if"
        #If your guess is too low, print a message and return to the "guess="
        if guess < number:
            #Notice the indentation here: nested whitespace
            print 'No, it is higher than that. Try again.' 
            #Otherwise ("else"), if your guess is too low, print another message and return to the "guess=" 
        elif guess > number: 
            print 'No, it is lower than that. Try again.' 
        #To reach here, your guess is neither too high nor too low. So you must have guessed correctly! 
        #Print a message and set got_it to True. 
        else: 
            print('Congratulations, you guessed it.') 
            print('(but you do not win any prizes!)') 
            got_it = True 
     
    #The indenting is now done. This means that the "while" block is finished. 
    #The following is the first command line after the while block. 
    print 'Done' 
    # This last statement is always executed, after the if statement is executed 


For reference, we will provide a few while loop templates that you can cut and paste into your programs. Here is a template for a loop that will count up.

#counting up loop
jstart = 1
jend = 100
j = jstart
while j<jend:
    #do some things here
    j += 1
 
#concluding action
print "Done while loop."

Here is a template for a loop that will count down.

#counting down loop
jstart = 100
jend = 1
j = jstart
while j>jend:
    #do some things here
    j -= 1
 
#concluding action
print "Done while loop."


Activity 7: Now create your own while loop from scratch. Do the following:

  • In Activity 4 of Part 2, we created a script that printed the radioactivity of a given sample every 10 years. The script can be found here . At the bottom of the script is a series of almost identical print statements. Use a while loop to replace these statements and allow the script to print out the activity every 20 years for 400 years. What is the activity at year 380?
  • Our solution script can be found here: The activity at year 380 is approximate 0.00077 µCurie.


Here is a template for a loop that will go on forever.

#loop that goes on forever
while True:
    #do some things here
 
#concluding action
print "We'll never get here."

In the above we could equivalently use
while True:
or
while (1==1):
or
while 1:
This type of loop is used frequently in Visual Python programming, where an animation is allowed to proceed until you close the window, which has the effect of restarting the Python shell. If you are ever in a situation where a function you made will go on forever (an infinite loop) you can restart the shell yourself by going to the Python shell and clicking Shell --> Restart Shell (or Ctrl + F6 for windows). This will stop anything that was running in the background and allow you to fix it without shutting down IDLE.

We conclude this section by revisiting an earlier Visual Python example and setting up a new one. First, here is the example "bounce.py" that we covered in Part 1.

from visual import *
 
floor = box(length=4, height=0.5, width=4, color=color.blue)
 
ball = sphere(pos=(0,4,0), color=color.red)
ball.velocity = vector(0,-1,0)
 
dt = 0.01
while 1:
     rate(100)
     ball.pos = ball.pos + ball.velocity*dt
     if ball.y < 1:
       ball.velocity.y = -ball.velocity.y
     else:
       ball.velocity.y = ball.velocity.y - 9.8*dt

Here's an outline of what this script does:

  1. The first line imports all the commands from the visual module of VPython.
  2. The second line defines a blue colored "box" object which has various attributes: length of 4, height of 0.5, etc.
  3. The third line defines a red colored "sphere" object with a specific position. Since no radius is specified, it has the default radius of 1.
  4. The fourth line indicates that the ball has a velocity property and that the velocity is initially downward on the screen.
  5. The fifth line defines a timestep that will define the position of the ball.
  6. The sixh line starts a while block. Since 1 evaluates to True, this while loop will run forever.
  7. The next few lines will be better explained elsewhere, but they basically say that the ball will fall under gravity (evaluated as 9.8 m/s²) until the ball touches the "floor", at which point its vertical velocity will reverse because of an elastic collision (bounce) with the floor. The rate(100) command controls the speed of the animation.


Activity 8: Do the following:

  • Open the file bounce.py included in the examples directory, or copy and paste the code above into a new file and save the file.
  • Then run the animation, trying to understand what the code is doing.
  • Explore further: print out some diagnostics, and alter the file to improve your understanding and generate different types of behaviour.


The next example is in the file linked at the end of this paragraph. It provides a visualization of the satellite-separation example above, using the VPython module. In this file, you can see the use of a "while" loop block and an "if" block embedded within it, as well as several function calls to the visual module. As with the bounce.py example, these functions will be covered more fully in the VPython tutorial. Here is the file:



5. Summary and Conclusion

A lot of different things were covered in this part of the tutorial. We introduced Booleans, conditional statements and while loops. Conditional statements including if, elif and else are used to see if a certain truth holds and complete some code afterward. These statements require checking whether or not an expression evaluates to either the True of False Boolean variable. If a statement evaluates to True, the if block will run, while if the statement evaluates to False, the if block will be skipped and the else block will be run. The last main topic covered in this tutorial is the while loop. While loops can used to accomplish many different tasks that involve repetition, but we must be careful to avoid infinite while loops. On a final note, remember the importance of indenting. Python evaluates your code using indentation as a guideline. Wrong indentation can result in your program not working, or worse, doing something that it is not intended to do.