003 Python-Commands
003 Python-Commands
Control Flow
Objectives
while <condition>:
<expression>
<expression>
...
Example While loop
It is never set to True anywhere. Therefore, the condition holds for all time
-
Known as an infinite loop – Easy to spot here, but not always so simple.
-
Break out of a loop
finished = False finished = False
while not finished: while not finished:
<do stuff> <do stuff>
if <found what we want>: if <found what we want>:
finished = True finished = True
<do more stuff> break Out of the while entirely!
<do more stuff>
Counting with Loops
• What if we wanted a fixed number of iterations?
counter = 0
while counter < 10:
# We can use pound to denote a commented line.
print(counter)
counter = counter + 1
# Much nicer syntax! This line is a comment.
for n in range(10):
print(n)
For loops
• range( start, stop, step )
• default start = 0, and step = 1 (these are optional)
• In computer science we count from zero
• Loop will iterate until stop – 1 → Stop is exclusive.
• Start is inclusive. sum_evens = 0
sum_numbers = 0 for i in range(0,12,2):
for i in range(5,10): sum_evens = sum_evens + i
sum_numbers = sum_numbers + i print(sum_numbers)
print(sum_numbers)
# This should be 5 + 6 + 7 + 8 + 9 → 35
# 0 + 2 + 4 … + 10 → 30
Revision Quiz
• Consider the following: Q: What’s the final value of
salary_summation = 0 salary_summation once the
for n in range( 5, 20, 5 ): program terminates?
print(n) Q: What if we changed == 15 to == 11 ?
What about >= 11?
salary_summation = salary_summation + n
if salary_summation == 15:
break
print("I’m rich!") ← Q: Does this ever get printed?
print("Current sum: ", salary_summation)
print("Adding up is hard")