Chapter 2. Control Flow
Chapter 2. Control Flow
Control flow
Contents
▪ Branching and conditionals
▪ Iteration and loops
2
Branching and conditionals
3
Comparison operators on int, float, string
▪ i and j are variable names
▪ comparisons below evaluate to a Boolean
i > j
i >= j
i < j
i <= j
i == j → equality test, True if i is the same as j
i != j → inequality test, True if i not the same as j
4
Logic operators on bools
▪ a and b are variable names (with Boolean values)
not a → True if a is False
False if a is True
a and b → True if both are True
a or b → True if either or both are True
A B A and B A or B
True True True True
True False False True
False True False True
False False False False
5
Comparison example
pset_time = 15
sleep_time = 8
print(sleep_time > pset_time)
derive = True
drink = False
both = drink and derive
print(both)
6
CONTROL FLOW - BRANCHING
if <condition>: if <condition>:
<expression> <expression>
<expression> <expression>
... ...
elif <condition>:
if <condition>: <expression>
<expression> <expression>
<expression> ...
... else:
else: <expression>
<expression> <expression>
<expression> ...
...
7
The IF Statement
Yes
x == 5 ?
x = 5 No print('Is 5’)
if x == 5: print('Still 5’)
print('Is 5‘)
print('Is Still 5’) print('Third 5’)
print('Third 5’)
8
Indentation Rules
• Increase indent after an if statement or for statement
(after : )
• Maintain indent to indicate the scope of the block
(which lines are affected by the if/for)
• Reduce indent to back to the level of the if statement
or for statement to indicate the end of the block
• Blank lines are ignored - they do not affect
indentation
• Comments on a line by themselves are ignored w.r.t.
indentation
9
Indentation Rules
increase / maintain after if or for
decrease to indicate end of block
blank lines and comment lines ignored
x=5 x=5
if x > 2 : if x > 2 :
print('Bigger than 2’) # comments
print('Still bigger’)
print('Done with 2’) print('Bigger than 2’)
# don’t matter
for i in range(5) : print('Still bigger’)
print(i) # but can confuse you
if i > 2 :
print('Bigger than 2’) print('Done with 2’)
print('Done with i’, i) # if you don’t line
# them up
10
INDENTATION
▪ matters in Python
▪ how you denote blocks of code
x = float(input("Enter a number for x: "))
y = float(input("Enter a number for y: "))
if x == y:
print("x and y are equal")
equal")
if y != 0:
print("therefore, x / y is", x/y)
x/y)
elif x < y:
print("x iss smaller")
smaller" )
else:
print("y iss smaller")
smaller" )
print("thanks!")
11
Warning: Turn Off Tabs
• Python cares a *lot* about how far line is indented.
If you mix tabs and spaces, you may get
“indentation errors” even if everything looks fine
• Most text editors can turn tabs into spaces - make
sure to enable this feature
12
Turn Off Tabs in Visual Studio Code
• Ctrl + Shift + P and choose “Convert Indentation to Spaces”
13
Turn Off Tabs in Sublimes
14
Two Way Decisions
• Sometimes we
want to do one x=4
thing if a logical
expression is
true and no yes
something else if x>2
the expression is
false print('Not bigger’) print('Bigger’)
• It is like a fork in
the road - we
must choose one
or the other path print('All Done’)
but not both
15
Two-way branch using else :
x = 4
if x > 2:
print('Bigger’)
else: x=4
print('Smaller’)
print('All done’)
no yes
x>2
print('All Done’)
16
Nested Decisions
yes
x>1
if x > 1:
print('More than one’) yes
x < 100
if x < 100:
print('Less than 100’)
no
print('Less than 100’)
print('All done’)
print('All Done’)
17
Chained Conditionals
if x < 2: yes
print('Small’) x<2 print('Small’)
print('LARGE’)
print('All Done’)
18
Chained Conditional
if x < 2:
print('Small’)
# No Else
elif x < 10:
x = 5
print('Medium’)
if x < 2:
elif x < 20:
print('Small’)
print('Big’)
elif x < 10:
elif x< 40:
print('Medium’)
print('Large’)
elif x < 100:
print('All done’)
print('Huge’)
else:
print('Ginormous’)
19
Multi-way Puzzles
• Which will never print?
if x < 2: if x < 2:
print('Below 2’) print('Below 2’)
elif x >= 2: elif x < 20:
print('Two or more’) print('Below 20’)
else: elif x < 10:
print('Something else’) print('Below 10’)
else:
print('Something else’)
20
Exercise
Write a pay computation program that gives the employee 1.5
times the hourly rate for hours worked above 40 hours (and
regular 1.0 rate for less than 40 hours)
Enter Hours: 45
Enter Rate: 10
Pay: 475.0
475 = 40 * 10 + 5 * 15
21
Exercise
• Write a program that prompts the user to input three stick
lengths, converts them to integers, and check whether sticks
with the given lengths can form a triangle.
• For example:
Input: 3 8 6
Output: YES
Input: 2 9 4
Output: NO
22
Exercise
• Return the number of days in the month of the Gregorian
calendar.
• The program ask the user to type the number of a month
and a year
23
Exercise
• Write a program to find all the roots of a quadratic equation
ax2+bx+c=0
24
Exercise
• Check whether the year you enter is a leap year or not
• In the Gregorian calendar, A leap year is a year containing
one extra day (366 days)
• Most years that are evenly divisible by 4 are leap years
• Years are evenly divisible by 100 are not leap year unless
they are evenly divisible by 400
25
Iteration and loops
26
CONTROL FLOW: while LOOPS
while <condition>:
<expression>
<expression>
...
▪ <condition> evaluates to a Boolean
▪ if <condition> is True, do all the steps inside the while
code block
▪ check <condition> again
▪ repeat until <condition> is False
27
CONTROL FLOW: while and for LOOPS
▪ iterate through numbers in a sequence
28
Repeated Steps
• Loops (repeated steps) have iteration variables that change
each time through a loop. Often these iteration variables go
through a sequence of numbers.
No Yes n = 5 5
n>0? while n > 0: 4
print(n) 3
print(n) n = n – 1 2
print(‘Blastoff!’) 1
n = n -1 print(n) Blastoff!
0
print('Blastoff’)
29
An Infinite Loop
• What is wrong with this loop?
n=5
No Yes n = 5
n>0?
while n > 0:
print('Lather’ ) print('Lather')
print('Rinse')
print('Dry off!')
print('Rinse’ )
print('Dry off!’)
30
Another Loop
• What does this loop do?
n=0
No Yes n = 0
n>0?
while n > 0:
print('Lather’ ) print('Lather')
print('Rinse’)
print('Dry off!')
print('Rinse’ )
print('Dry off!’)
31
break STATEMENT
▪ immediately exits whatever loop it is in
▪ skips remaining expressions in code block
▪ exits only innermost loop!
while <condition_1>:
while <condition_2>:
<expression_a> break
<expression_b>
<expression_c>
32
Breaking Out of a Loop
• The break statement ends the current loop and jumps to
the statement immediately following the loop
33
while True:
line = input('> ') No Yes
True ?
if line == 'done':
break ....
print(line)
print('Done!')
break
...
print('Done’)
34
Using continue in a loop
• The continue statement ends the current iteration and
jumps to the top of the loop and starts the next iteration
35
while True: No
line = input('> ') True ? Yes
if line[0] == '#':
continue ....
if line == 'done':
break continue
print(line)
print('Done!')
...
print('Done’)
36
Indefinite Loops
• While loops are called "indefinite loops" because
they keep going until a logical condition becomes
False
• The loops we have seen so far are pretty easy to
examine to see if they will terminate or if they will
be "infinite loops"
• Sometimes it is a little harder to be sure if a loop
will terminate
37
Definite Loops
• Quite often we have a list of items of the lines in a file -
effectively a finite set of things
• We can write a loop to run the loop once for each of the
items in a set using the Python for construct
• These loops are called "definite loops" because they
execute an exact number of times
• We say that "definite loops iterate through the members of
a set"
38
CONTROL FLOW: for LOOPS
for <variable> in range(<some_num>):
<expression>
<expression>
...
▪ each time through the loop, <variable> takes a
value
▪ first time, <variable> starts at the smallest value
▪ next time, <variable> gets the prev value + 1
▪ etc.
39
A Simple Definite Loop
5
4
3
2
1
Blastoff!
40
A Simple Definite Loop
41
A Simple Definite Loop
• Definite loops (for loops) have explicit iteration variables
that change each time through a loop. These iteration
variables move through the sequence or set.
No
Yes
Done? for i in [5, 4, 3, 2, 1]:
print(i)
print('Blastoff!')
Move i ahead
5
4
Print(i) 3
2
1
Print('Blast off!') Blastoff!
42
The range(start, stop, step) function
• range() is a built-in function x = range(5)
that allows you to create a print(list(x))
sequence of numbers in a [0, 1, 2, 3, 4]
range
• Very useful in “for” loops x = range(3, 7)
which are discussed later in print(list(x))
the Iteration chapter [3, 4, 5, 6]
• Takes as an input 1, 2, or 3
arguments. See examples. x = range(10, 1, -2)
print(list(x))
• default values are start = 0 [10, 8, 6, 4, 2]
and step = 1 and optional
• loop until value is stop – 1 if
the step value is positive or
stop + 1 if the step value is
negative
43
A Simple Definite Loop iterating over a range
for i in range(7, 0, -1):
print(i)
print('Blastoff!')
7
6
5
4
3
2
1
Blastoff!
44
Question
• What happens in this program?
45
Looking at in
• The iteration variable “iterates” though the sequence
• The block (body) of code is executed once for each value in
the sequence
• The iteration variable moves through all of the values in the
sequence
Five-element sequence
Iteration variable
46
Looping through a Set
Print('Before')
for thing in [9, 41, 12, 3, 74, 15]:
print(thing)
print('After')
Before
9
41
12
3
74
15
After
47
Counting in a Loop
• To count how many times we execute a loop we introduce a
counter variable that starts at 0 and we add one to it each
time through the loop.
zork = 0 Before 0
print('Before', zork) 19
for thing in [9, 41, 12, 3, 74, 15]: 2 41
zork = zork + 1 3 12
print(zork, thing) 43
print('After', zork) 5 74
6 15
After 6
48
Summing in a Loop
• To add up a value we encounter in a loop, we introduce a
sum variable that starts at 0 and we add the value to the
sum each time through the loop.
zork = 0
Before 0
print('Before', zork)
99
for thing in [9, 41, 12, 3, 74, 15]:
50 41
zork = zork + thing
62 12
print(zork, thing)
65 3
print('After', zork)
139 74
154 15
After 154
49
Finding the Average in a Loop
• An average just combines the counting and sum patterns
and divides when the loop is done.
count = 0 Before 0 0
sum = 0 199
print('Before', count, sum) 2 50 41
for value in [9, 41, 12, 3, 74, 15]: 3 62 12
count = count + 1 4 65 3
sum = sum + value 5 139 74
print(count, sum, value) 6 154 15
print('After', count, sum, sum / count) After 6 154 25
50
Filtering in a Loop
• We use an if statement in the loop to catch / filter the
values we are looking for.
print('Before')
for value in [9, 41, 12, 3, 74, 15]:
if value > 20:
print('Large number’, value)
print('After')
Before
Large number 41
Large number 74
After
51
Search Using a Boolean Variable
• If we just want to search and know if a value was found - we
use a variable that starts at False and is set to True as soon
as we find what we are looking for.
52
Finding the smallest value
• We still have a variable that is the smallest so far. The first
time through the loop smallest is None so we take the first
value to be the smallest.
smallest = None Before
print('Before') 99
for value in [9, 41, 12, 3, 74, 15]: 9 41
If smallest is None : 9 12
smallest = value 33
elif value < smallest: 3 74
smallest = value 3 15
print(smallest, value) After 3
print('After', smallest)
53
The "is" and "is not" Operators
• Python has an "is" operator that can be used in logical
expressions
• Implies 'is the same as'
• Similar to, but stronger than ==
• 'is not' also is a logical operator
smallest = None
print('Before')
for value in [3, 41, 12, 9, 74, 15]:
if smallest is None:
smallest = value
elif value < smallest:
smallest = value
print(smallest, value)
print('After', smallest)
54
for vs while loops
for loops while loops
▪ know number of ▪ unbounded number of
iterations iterations
▪ can end early via ▪ can end early via break
break ▪ can use a counter but
must initialize before loop
▪ uses a counter and increment it inside loop
▪ can rewrite a for loop ▪ may not be able to
using a while loop rewrite a while loop using
a for loop
55
Exercise
• Write a program to print odd positive integers less than n in
descending order
56
Exercise
• Write a program to input number n and print its factorial
57
Exercise
• Calculate sum of harmonic series 1 +1/2+…+1/n
58
Exercise
• An Amstrong number of 3 digit is an integer that the sum of
the cubes of its digits is equal to the number itself. Find
Amstrong numbers of 3 digits.
59
Exercise
• Calculate sum of the first n integers except those divisible by
5
60
Exercise
• The mathematician Srinivasa Ramanujan found an infinite
series that can be used to generate a numerical
approximation of 1 / π:
61
References
1. MIT Introduction to Computer Science and Programming
in Python
2. Think Python: How to Think Like a Computer Scientist:
https://greenteapress.com/thinkpython2/html/index.html
62
Thank you for
your attention!
63