Flow control
Chris Rowlands
Stuff-I-got-interested-in-this-week group
Flow control
Learning outcomes
• Understand the concept of a while loop, for loop and an if/then/else
(conditional) statement
• Be able to implement while loops, for loops and conditional statements in
Python
• Be aware of some more unusual features like iterators, break statements,
else statements, do-while loops
Flow control
Outline
• while
– “indefinite iteration”
• for
– “definite iteration”
• if / else
– “conditional statements”
• Bringing it all together
– Some more advanced topics
Flow control
While loops
• Repeat a series of instructions until a condition is
fulfilled
– Loop body doesn’t necessarily execute
• Can create an infinite loop
– Commonly used as a main loop
• Most languages let you break a loop explicitly
Flow control
Python While loops
• Note the significant whitespace! while <expr>:
– Indents denote loop contents <statement(s)>
• You can use any number of spaces
spam = 0
or tabs but each line of the loop must
while spam < 5:
have the same number.
print(spam)
• Note that all integers, floats or spam = spam + 1
complex numbers will be evaluated
as True, apart from 0 which spam = 5
evaluates to False while spam:
print(5-spam)
spam = spam - 1
Flow control
Test your knowledge!
• For a given combination of positive integers a, b and c, what is the smallest
number which is divisible by all three?
– Pseudocode is acceptable
Flow control
For loops
• Repeat a statement a fixed number of times
• Special case of a while loop
– Can often be optimized better by the compiler /
interpreter than a more generic while loop
– Can often be explicitly vectorized / run in parallel
for N iterations:
<do something>
end for
Flow control
For loops: Traditional vs Iterators
• Traditional for loops: increment the loop variable each time, test it each loop
for some termination condition
• Iterators: The loop variable takes the next value in a sequence / collection /
set / list each time.
– The sequence doesn’t need to be explicitly calculated ahead of time
– Sometimes it guarantees to execute in the order of the list, sometimes it
doesn’t (language dependent)
Flow control
For loops in Python
• Significant whitespace again for i in range(0, 6):
• Python 3 uses iterators print(i)
– Use the range() function when
you want to create an arithmetic 0
progression 1
– You can also iterate over a list 2
3
sketchList = ['spam', 'eggs', 4
'ham'] 5
for food in sketchList:
print(food)
spam
eggs
ham
Flow control
Test your knowledge!
• Given a random list of numbers, print the value of each number in the list
divided by 10
– Pseudocode is acceptable
Flow control
If statements
• Also known as conditional statements
• Execute separate statements based on
a condition check
• “Else if”: if the conditions above are not
fulfilled, check to see if this condition is,
and execute the following code
– Can have lots of these
• “Else”: execute this code if none of the
preceding conditions are fulfilled.
Flow control
If statements in Python
• Syntax: if testCondition:
# do something
elif testCondition2:
# do something else
else:
# do something else entirely
• Note elif and else are optional.
• Significant whitespace!
• Colon needed
Flow control
If statements in Python
var = 0.0
if type(var) == int:
print('var is an integer')
elif type(var) == float:
print('var is a float')
elif type(var) == str:
print('var is a string')
else:
print('I have no idea what type var is')
Flow control
Break and Continue statements
• break allows you to exit a loop early
– Useful if you’re in an infinite loop, or you’ve found something you’re
looking for
• continue lets you stop executing that loop, and immediately jump to the
next one.
– Useful when you don’t want to process certain inputs
• Some languages let you re-evaluate the current iteration of the loop
– Some languages even let you restart the loop from the beginning
– Neither Python nor C support this
Flow control
Do-While
• Always executes the loop at least once
• Not present in Python, but can be implemented with a
while loop and a break statement:
spam = 5
while True:
print(spam)
spam = spam - 1
if spam == 0:
break
Flow control
Using the IDLE debugger
• Step
– Execute the current line and
move to the next
• Over
– Skip over a loop or function,
and go to the next line in the
program after that
• Out
– If you’re already in a loop or
function, finish executing it
and then go to the next line
in the program
Flow control
Test your knowledge! – combining everything
• Given a random list of numbers, count how many positive and negative
numbers there are
– Pseudocode is acceptable
Flow control
Test your knowledge! – combining everything
• How would you (automatically) determine how many letters into the tongue-
twister “How much wood could a woodchuck chuck if a woodchuck could
chuck wood?” the third instance of the word “chuck” is?
– “Pseudocode” answers OK; real Python code is just a bonus
Flow control
Summary
• Loops
– While
– For
– Do while
• Conditionals
– If, elif, else
• Advanced topics
– Break, continue
• Debugging