Program Flow Control
Booleans
The bool
data type is used to represent . 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 the comparison operators to create an expression 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 |
Expression | Result |
---|---|
True or True | True |
True or False | True |
False or True | True |
False or False | False |
Expression | Result |
---|---|
not True | False |
not False | True |
You can mix the two 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')
Note how the code that should execute when 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
if
statements can be , using deeper indentation.
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))
[Click here to visualize the execution]
Teenager
Female
Girl
Gender code is F
Age is 13
If a situation has only two possibilities e.g. if we assume the value of 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.
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'.
| → |
[Click here to visualize the execution] |
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.
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.')
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)
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
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))
While a range normally starts from 0
and goes until the specified end number, you can specify a starting number for a range
e.g., range(5, 8)
gives you 5 6 7
.
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)
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 into 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 directly use in your code as if the function is already in your code file, 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 themath
module)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.
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