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

Contact: compwiki@physics.utoronto.ca

Last updated around: 2018-07-25

This section moves into slightly more advanced concepts related to flow control, i.e. decisions that are made in a program based on logical tests for equality or inequality.

We will introduce logical statements, logical variables and if statements(current link is for Python 2 documentation). We will then introduce while loops, which are controlled by logical conditions.

## 1. Review

First, let's review where we stand. We've learned a bit about

• Basic calculations and variables,
• Taking user input and using it in our own code,
• Using import to use programs others have written and how to define our own functions.

Even with what we've learned so far we can accomplish a broad range of tasks using Python.

Here's a review exercise focusing on functions.

#### Review Exercise: Activity 0

Let's define a function that makes some predictions from the theory of special relativity. Consider an object whose length (along the x-axis) and mass in a resting frame are L and m, respectively. If this object is in motion with velocity v with a speed less than the speed of light (|v|<c) along the x-axis, its length and mass become Now do the following:

• Take a look at the following code block (function definition block).
• Try to predict its behaviour by walking through each line.
• (Do you notice that the apostrophe "s" in the first print statement has a backslash \? The backslash is an escape character in Python that allows the interpreter to treat the apostrophe (single quote) as punctuation instead of a string delimiter.)
• Then copy and paste it into a new window in Spyder and save it.
python code
            def special_rel():
print('Let\'s calculate the length along the x-axis and relativistic mass')
print('for an object moving along the x direction with velocity v, with |v|<c.')
l = input('Enter the resting length along the x-axis, in m: ')
l = float(l)
m = input('Enter the resting mass of the object, in kg: ')
m = float(m)
v = print('Enter the velocity v in the x direction in units of ')
v = input('the speed of light, c. Make sure that |v|<1! ')
v = float(v)
gamma = (1-v**2)**(-0.5)
m_prime = gamma * m
l_prime = l/gamma
print('The gamma factor is :', gamma)
print('The relativistic mass of the object is: ', m_prime, ' kg.')
print('The relativistic length of the object is: ', l_prime,' m.')
return m, l, v, gamma, m_prime, l_prime

• Now click Run --> Run Module or hit F5.
• Now, in the Spyder console, type special_rel() and follow the instructions on the screen.
• What happens to the mass and length of the moving object? Does this make sense?

This code is really easy to 'break' because, if you don't follow instructions and enter a value for v whose magnitude is greater than the speed of light (|v|>c), you will get back strange results.

• Try this out now (in other words enter a number greater than 1 or less than -1 for the velocity).
• Can you explain the result? [Don't worry if you can't for now.]
• Notice that in this program we returned all the values in case they could be of use in another program. To capture these values, you can type something like
python code
            my_m, my_l, my_v, ,my_gamma, my_m_prime, my_l_prime = special_rel()


If you print(my_m) or any of the other variables you will find that you have saved these variables for reuse.

• Typing special_rel() is called calling the function. Once you've defined your function you can call it over and over again until you restart the 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

python code
            2 < 3


in the console will result in the answer True (prompts omitted):

python code
            2 < 3
True


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

python code
            2 > 3
False

• Verify this now in the Python shell (Spyder console).

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, 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 older Python programs.

To test equality, Python uses the double equals sign, ==, so (prompts omitted):

python code
            1 == 1
True


but

python code
            1 == 0
False


The comparison operators which you will need to use are <, <=,==,!=, >=, >, which respectively mean less than, less than or equal to, equal to, not equal to, greater than or equal to, and greater than.

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

python code
            In : 1 == 1 and 1<2
Out: True

In : 1 == 1 and 1>2
Out: False

In : 1 == 1 or 1 > 2
Out: True

In : 1 != 1 or 1 > 2
Out: False

In : not 1 == 1
Out: 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 (prompts omitted):
python code
            2 == 3
"apple" == "orange"
from numpy import pi; pi < 3.14

• In the second line, "apple" and "orange" are strings(current link is for Python 2 documentation), 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:

python code
            a = 2; b = 3
a_is_two = (a==2) #check if a is 2
print(a_is_two)


The result will be

python code
            True

python code
            b_is_two = (b==2) #check if b is 2
print( b_is_two) #print result


The result will be

python code
            False


#### Activity 2: Do the following

• Predict the outcome of the following, and try them in the Python shell.
python code
            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(current link is for Python 2 documentation). For example

python code
            if 2 < 3: print("hello")

• You can try typing this in the Spyder console. 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

python code
            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.

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

• To use this code, copy and paste it as usual, either in a file or in the console.
• Notice that the if code block uses the same kind of indentation as the def (function) code block. The points about indentation are the same for any code block:
• The number of spaces from the left margin is up to you, but the indentation must be consistent from line to line.
• The Spyder and other editors and consoles and shells will try to help you with indentation of code blocks code as you create scripts. Pay attention to the indentation and the coloured fonts - they will highlight potential bugs.
• 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.

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.

python code
            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 5 (harder): Returning to Activity 0, write a function that returns without doing further calculation if the condition |v|<c is violated.

• One solution to this can be found here. This solution uses the abs() built-in function, which returns the absolute value of its argument.

## 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:

python code
            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 6: The following program illustrates the while loop and might be useful for the Canadian Space Agency to assist with countdown procedures. Do the following:

• Copy/paste/run the script.
• Once you've seen the script run, read the comments to understand what it's doing.
python code
            #Countdown
current_count = 10
#Execute 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 7: Before delving into the program, do the following:

• Cut/paste/run the program.
• You can use this program as a template for nested "while" plus "if/elif/else" blocks.
python code
            #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 guess < number:
#Notice the indentation here: nested whitespace
print( 'No, it is higher than that. Try again.')
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.
python code
            #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.
python code
            #counting up loop
jstart = 100; jend = 1
j = jstart
while j>jend:
#do some things here
j -= 1
#concluding action
print( "Done while loop.")


#### Activity 8: 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 approximately 0.00077 µCurie.

Non-terminating while loops: Sometimes you want a while a loop that will go on "forever". This could be for animations or for selection in which a condition for breaking out of the loop is contained inside the while block.

• Here is a template for a loop that will go on forever.
python code
            #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:, while (1==1):, or while 1:.

## 5. Summary and Conclusion

In this tutorial,

• We introduced boolean values, variables, and logical (conditional) statements.
• We introduced if conditional statements/blocks 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.
• While loops can used to accomplish many different tasks that involve repetition, and for non-terminating while loops, infinite repetition.
• Throughout the tutorial we were reminded of the special rules about Python indentation.
• 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.

Part_3_Solutions..pdf
This concludes Part 3 of the Tutorial. Please proceed to Tutorial Part 4.