Program Flow Control
Booleans
The bool data type is used to represent boolean values (i.e. true/false values). They are useful when the program execution needs to vary based on a certain condition e.g., print 'old' if age is greater than 100.
The bool data type can hold only two values True and False (case sensitive).
>>> type(True)
<class 'bool'>
>>> type(False)
<class 'bool'>
>>> type('True')
<class 'str'>
>>> type(true)
...
NameError: name 'true' is not defined
You can use comparison operators to create expressions that evaluate to a boolean result.
| Operator | Meaning |
|---|---|
== |
Equal to (different from the assignment operator =) |
!= |
Not equal to |
< |
Less than |
> |
Greater than |
<= |
Less than or equal to |
>= |
Greater than or equal to |
📦 Here are some examples
print('hello' == 'Hello') # False
print('dog' != 'cat') # True
print(True == True) # True
print(True != False) # True
print(42 == 42.0) # True (they are different types of numbers, but of same value)
print(42 == '42') # False
print(42 == int('42')) # True
print(20 > 10) # True
In contrast, boolean operators (and, or and not) work only on boolean values. Here is how they work.
| Expression | Result |
|---|---|
True and True |
True |
True and False |
False |
False and True |
False |
False and False |
False |
True or True |
True |
True or False |
True |
False or True |
True |
False or False |
False |
not True |
False |
not False |
True |
You can mix both types of operators. Some examples below:
result = (2 > 5) or (10 < 20) # True
result = (2 == 2) and (3 != 3) # False
if Statements
Python uses the if statement to indicate that some code should only be executed if a certain condition is true.
Format:
if condition :
statements_to_execute_if_true
📦 The code below has two if statements; one evaluates to true while the other doesn't.
price = 55
print(price)
if price > 50:
print('Expensive')
weight = 45
print(weight)
if weight > 100:
print('Heavy')
print('Done')
Output ⤵️
50
Expensive
45
Done
Use the Back and Forward buttons to visualize execution one step at a time.
If the space below is blank, you may need to configure your browser to allow loading the required javascript file. Alternatively you can go to PythonTutor.com, copy-paste the above Python code there to see the execution steps.
Note how the code to execute if the condition is true is indented (usually by 4 spaces). Python uses indentation to indicate code blocks (aka clauses) i.e., a sequence of statements that belong together. In the example below, lines 2-4 are in the same block because they are all indented by one level; if the condition is true, all three are executed; if the condition is false, all three are omitted. Line 5 goes back to the previous indentation level, indicating the end of the code block.
if name == 'Blue': # line 1
print("It's a color") # line 2
print("It's a feeling") # line 3
print("It's a word") # line 4
print('Done') # line 5
Exercise : Even Numbers
Write a program to read an integer from the keyboard and print 'Even' only if it is an even number. Follow the example below:
Enter an integer:
4
Even number
Done
Enter an integer:
7
Done
if statements can be
age = 13
gender = 'F'
if (age > 12) and (age < 20):
print("Teenager") # indented one level - new code block starts here
if gender == 'F':
print('Female')# indented two levels - this block is nested within the first block
print('Girl')
if gender == 'M':
print('Male') # another block nested within the first block
print('Boy')
print('Gender code is ' + gender)
print('Age is ' + str(age))
⤵️
Teenager
Female
Girl
Gender code is F
Age is 13
If a situation has only two
gender can only be M or F, we can use the else statement to deal with both conditions together.
📦 In the example below, the entire else block will be skipped if the if condition is true.
if gender == 'F':
print('Female')
else:
print('Not Female')
If a situation has more than two mutually exclusive possibilities, we can bring in elif (an abbreviation of else if) blocks too.
📦 The example below shows how to use an if-elif-else construct to control the flow of the execution.
if gender == 'F':
print('Female')
elif gender == 'M':
print('Male')
elif gender == 'O':
print('Other')
else:
print('Unrecognized value')
Note that in an if-elif-else construct no more than one block (the first one whose condition is true) will be executed.
Exercise : Grade Analyzer
Write a program to read project score and exam score from the keyboard and print a bar chart of the scores and a grade. Follow the example below:
Enter project score:
30
Enter exam score:
40
Total: 70
Project : ======
Exam : ========
Total : ==============
Grade : A
- Note how the colons are aligned.
- Note the extra blank lines in the expected output.
- The bar chart has one
=for each 5 marks 24 marks should be shown as====. - Assume all inputs are positive integers.
Grading rules:
A: at least 25 marks for each component and at least 60 in totalB: at least one component has 25 or more marks and at least 50 in totalC: at least 40 in totalD: otherwise
Exercise : Grade Analyzer (Extended)
Extend the code you wrote for the exercise Grade Analyzer with the following additional feature.
If the grade is determined to be D ask the user if the grade should be withheld. If the user agrees, show the grade as NA instead of D.
Enter project score
10
Enter exam score
20
Total: 30
Grade is low. Withhold? y/n?
y
Project : ==
Exam : ====
Total : ======
Grade : NA
while Statements
Python uses the while statement to repeat a code block until a certain condition is true. Such an execution path is also known as a loop and each execution of the code block is called an iteration.
Format:
while condition :
statements_to_execute_if_condition_is_true
📦 the code below prints 'Hello' 3 times (i.e., the loop is executed for 3 iterations), followed by 'Done'.
|
→ |
|
❗️ Infinite Loops: Sometimes programming mistakes can result in infinite loops i.e., loops that never terminate. In the example below, the condition counter < 3 always evaluates
to True (because the statement to increment counter has been left out by mistake)
counter = 0
while counter < 3:
print('Hello')
💡 When using IDLE, if a bug in your code caused it to go into an infinite loop, you can use Ctrl + C to force it to stop executing.
Exercise : Vending Machine - Add Loop
The code below simulates a vending machine that asks for a coin and gives out the product and the balance.
price = 100
coin_value = 0
print('Price:', price)
coin_value = int(input('Enter a coin:'))
print('You have entered:', coin_value)
print('Here is the product')
print('Your balance:', coin_value - price)
💡 Note how the above code uses input function with a string argument e.g., input('Enter a coin:') to show the string to the user and read the input from the user at the same time.
|
→ |
|
|
→ |
|
💡 Also note how the above code uses print() with two parameters, one an integer and one a string. The print() method can take multiple parameters and the parameters can be of different types. Note that the output will have a space between each parameter.
|
→ |
|
Example output from the code:
Price: 100
Enter a coin: 200
You have entered: 200
Here is the product
Your balance: 100
As you can see, this code does not consider the case where the inserted coin is less than the price of the product, resulting in the following incorrect behavior.
Price: 100
Enter a coin: 50
You have entered: 50
Here is the product
Your balance: -50
Modify the code to repeat these two lines until the coin entered is enough to pay for the product. Note that you don't need to add up all the coins entered. Instead, assume the vending machine can accept only one coin for a purchase and keeps rejecting coins until a big-enough coin is entered.
coin_value = int(input('Enter a coin:'))
print('You have entered:', coin_value)
The output should be something like this:
Price: 100
Enter a coin: 50
You have entered: 50
Enter a coin: 100
You have entered: 100
Here is the product
Your balance: 0
Exercise : Vending Machine - Accept Multiple Coins
The vending machine you wrote in the previous exercise (an example solution given below) can accept only one coin as the payment. If the coin is not enough, it rejects the coin and request the user to insert a new coin.
price = 100
coin_value = 0
print('Price:', price)
while price > coin_value:
coin_value = int(input('Enter a coin:'))
print('You have entered:', coin_value)
print('Here is the product')
print('Your balance:', coin_value - price)
Modify the code so that it can accumulate coins until there is enough to pay for the product. An example output is given below:
Price: 100
Enter a coin: 20
You have entered: 20
Enter a coin: 50
You have entered: 70
Enter a coin: 50
You have entered: 120
Here is the product
Your balance: 20
...
coin_sum = 0
...
coin_sum = coin_sum + coin_value
...
You can use a break statement to break out of a loop.
📦 The code below uses the break statement to break out of the loop when the password given is abcd. Without the break statement, the loop will repeat forever because the condition in while True: is always True.
while True:
password = input('What is the password?')
if password == 'abcd':
break # exit the loop
else:
print('Password incorrect. Try again.')
print('Password correct. You may proceed.')
Exercise : Vending Machine - Allow Abort
The vending machine you wrote in the previous exercise (an example solution given below) does not allow the user to abort the purchase and get the money back.
price = 100
coin_sum = 0
print('Price:', price)
while price > coin_sum:
coin_value = int(input('Enter a coin:'))
coin_sum = coin_sum + coin_value
print('You have entered:', coin_sum)
print('Here is the product')
print('Your balance:', coin_sum - price)
Modify the code so that the user can abort the purchase by entering 0 as the coin value:
Price: 100
Enter a coin: 20
You have entered: 20
Enter a coin: 0
Your balance: 20
...
is_aborting = False
...
if coin_value == 0:
is_aborting = True
break
...
if is_aborting:
print('Your balance:', coin_sum)
You can use a continue statement to skip the remainder of the current iteration and go back to the while condition.
📦 The code below is for reading three words from the user and printing all three at the end. It uses the continue statement to skip the remainder of the iteration if the word entered is too short (i.e., shorter than 4 letters).
accepted_words = ''
count = 0
while count < 3:
word = input('Enter a word (with 4 letters or more):')
if len(word) < 4:
print('Too short. Ignored.')
continue # skip the remainder of the iteration
accepted_words = accepted_words + ' ' + word
count = count + 1
print('Accepted words: ' + accepted_words)
Exercise : Vending Machine - Legit Coins
The vending machine you wrote in the previous exercise (an example solution given below) accepts any value as the coin value. However, coins come in only certain values only.
price = 100
coin_sum = 0
is_aborting = False
print('Price:', price)
while price > coin_sum:
coin_value = int(input('Enter a coin:'))
if coin_value == 0:
is_aborting = True
break
coin_sum = coin_sum + coin_value
print('You have entered:', coin_sum)
if is_aborting:
print('Your balance:', coin_sum)
else:
print('Here is the product')
print('Your balance:', coin_sum - price)
Modify the code so that it accepts coins of value 10, 20, 50, 100 only:
Price: 100
Enter a coin: 30
Coin not recognized
Enter a coin: 100
You have entered: 100
Here is the product
Your balance: 0
...
if coin_value != 10 and ... :
...
continue
...
for Statements
You can use a for statement, together with the range() function, to repeat a code block a pre-determined number of times.
Format:
for variable_used_as_index in range(number_of_times_to_repeat) :
statements_to_repeat
📦 the code below use a for loop to iterate three times. Note how the variable i is used as an indexing variable and how i in range(3) causes i to take values 0, 1, 2 over the three
iterations.
|
→ |
|
💡 Note how the above for loop is equivalent to the following while loop but more concise.
i = 0
while i < 3:
print(i, 'Knock knock, Penny!')
i = i + 1
Exercise : Multiplication Table
Write a program to read in an integer and generate the multiplication table (for 1 to 10) for that number. An example is given below:
Enter a number: 7
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70
for i in range(10) iterates from 0 to 9. You can use range(1, 11) to iterate from 1 to 10.
You can use break and continue in for loops as well, with similar effects as in while loops.
📦 The code below totals the numbers entered by the user. It uses range(5) to limit the number of entries to 5. It uses a break to exit the loop if user hits Enter without entering a value. It uses a continue statement to skip negative numbers entered by the user.
total = 0
for n in range (5):
number_as_string = input('Enter a number (press enter to exit):')
# exit if user input is empty
if number_as_string == '':
print('Exiting as per user request...')
break
# convert the input into an integer
number_as_int = int(number_as_string)
# skip if the number is negative
if number_as_int < 0 :
print('Negative number, skipped')
continue
# update the total and print the running total
total = total + number_as_int
print('Running total:' + str(total))
print('Grand total of non-negative numbers:', str(total))
Exercise : Multiplication Table (Extended)
Modify the code a program to,
- print multiplication values of up to
x 20(not up tox 10as before) - omit squares (i.e.
n*n). Note how8 x 8has been omitted in the example below. Recommended: use acontinuestatement to achieve this. - not print rows that has a value higher than 100. Note how the printing stops after
8 x 12 = 96in the example below. Recommended: use abreakstatement for this.
Enter a number: 8
8 x 1 = 8
8 x 2 = 16
8 x 3 = 24
8 x 4 = 32
8 x 5 = 40
8 x 6 = 48
8 x 7 = 56
8 x 9 = 72
8 x 10 = 80
8 x 11 = 88
8 x 12 = 96
Loops can be nested.
📦 The code below use two nested for loops to print multiplication tables for 2, 3, and 4.
for i in range(2, 5):
print('Multiplication table for', i)
for j in range(1, 11):
print(i, 'x', j, '=', i*j)
Exercise : Three Dice Throws
Write a program to generate all possible results you can get by throwing a
1 1 1
1 1 2
1 1 3
1 1 4
1 1 5
1 1 6
1 2 1
1 2 2
...

source: wikipedia
Use three nested for loops.
Importing Modules
In addition to built-in functions such as print(), input(), and len(), Python has a set of functions called the standard library. Functions in the standard library are divided
in to modules. A module is a python program that contains a related group of functions. You can think of it as a file containing some python functions.
📦 Some example modules in the Python standard library:
| Name | What it contains |
|---|---|
math |
mathematics-related functions |
random |
random number–related functions |
sys |
provides ways to interact with the Python interpreter |
Unlike built-in functions which you can use simply use in your code, to use a function in the standard library you need to import the corresponding module first.
Format: import module_name(s)
📦 Some examples:
import math(imports themathmodule)import math, sys, random(imports all three modules in one statement)
Furthermore, to use a function from an imported module, you should use the module_name.function_name() format.
📦 the code below imports the random module and uses its randint() function to generate a number between 1 and 10.
import random
print('Going to print 5 random numbers between 1 and 10')
for i in range(5):
print(random.randint(1, 10))
💡 It is common practice to put the import statements at the top of the program code.
Exercise : Circle Area
Write a program to read the radius of a circle (a float number) from the input and print the area of the circle, rounded to five decimal places.
💡 some useful hints:
- Area = PI * radius2
- You can use
math.pias the value of PI. - You can use the built-in function
roundto round off a number to a specified number of decimal places. e.g.,round(1.12345, 2)returns1.12
Enter radius: 4.5
Area: 63.61725
Early Termination
At times you may need to terminate a program execution early i.e., without reaching the end of the code. You can use the exit() function in the system module to terminate a program early.
📦 The code below prints out the factorials of 1 to n where n is specified by the user. If n is 0, it uses sys.exit() to terminate the program immediately.
import math, sys
n = int(input('Number of factorials (0 to exit):'))
if n == 0:
print('Terminating as requested...')
sys.exit()
for i in range(n):
print(math.factorial(i+1)) # use i+1 because i starts from 0