10. Loops
if/elseare great for having a block of code run when some condition isTrueSometimes we need a block to repeatedly run while some condition is
True
10.1. Reusing and Updating Variables
Before we look at loops, consider the following code
1a = 5
2print(a)
3
4b = 6
5print(a)
6
7a = a + b
8print(a)
9
10a = 3
11a = a + 1
12print(a)
Activity
What is the value of a at each print statement? In other words, a is printed out four times — what values
are printed out?
The point being emphasized is that there is nothing stopping us from reusing variables
Assign a value to some variable
Update/change the value stored in that variable
A very common pattern for incrementing the value of some variable in programming is as follows
1a = a + 1
The above example will add one to whatever value is stored in
aand then store that new value back toaFor example
If
astarts with the value5Calculate
a + 1, which is6in this exampleStore the newly calculated value of
6ina
This and similar patterns are so common that many programming languages have shorthand operators for this
1a += 1 # Effectively the same as a = a + 1
The above example is effectively identical to the previous
It means, add
1toaand put the newly calculated value back intoa
Activity
Start with a = 5.
Figure out what
a += 2does.See what happens when you use
a *= 2.Try other operators to see what works.
10.2. While loops
So far, if we need to run the same code multiple times, we repeat the code as many times as we need
For example, if I wanted to
print("Hello, world!")five times, I need to write that print statement 5 times
The trouble with this is
It’s tedious
It doesn’t scale well
It’s prone to errors
It will not work for some variable number of times
For example, what if I want to print
ntimes wherenis some parameter to a function
This is where the
whilestatement comes inIt will repeat some code
whilesome condition isTruewhile some_condition:The indented code will run while the condition is
True
1counter = 0
2while counter < 10:
3 print(counter)
4 counter += 1
The above example will print out the numbers
0–9We initialized a
countervariable outside the loopBefore each iteration, Python checks the
whileconditionIf the condition is
True, the indented code runsprintout the value ofcounterIncrement
counterRepeat the loop until the condition is
False
Warning
Off-by-one errors are very common when writing loops. For example, be careful about whether your stopping condition should include the final value or stop before it.
Starting with counter = 0:
while counter < 10:prints0through9Runs 10 times
while counter <= 10:prints0through10Runs 11 times
Activity
What would happen if counter += 1 was not included in the loop? Try to answer based on what you know. Confirm
what happens by trying to run the code.
To stop the infinite loop, select the stop button in Colab.
A loop usually needs something inside to change, otherwise the condition may never become False.
10.2.1. Tracing Through A Function By Hand
Trace through the below code by hand for a few values of
nSee if you can figure out what this function is doing
Note that
n -= 1is short hand forn = n - 1
1def trace_through_me_by_hand(n: int) -> int:
2 result = 1
3 while n > 1:
4 result = result * n
5 n -= 1
6 return result
whileloops can get complex quicklyComments here would have helped make the intent clearer
When tracing through the code, don’t try to do it all in your head
Create a table to keep track of the values
Below is an example with
trace_through_me_by_hand(4)
n |
result |
|---|---|
4 |
1 -> 4 |
3 |
4 -> 12 |
2 |
12 -> 24 |
1 |
Stop |
Activity
Write a function called int_sum(n) that takes a single integer n as a parameter and returns the sum of all
the numbers between 0 and n inclusively (include n in the summation).
When you finish writing the function, do not run it right away — trace through the program by hand like with the
trace_through_me_by_hand above.
Activity
Create a new function called int_sum_print that is the same as int_sum, however this function should
print out the values of all the variables each time in the loop. Ideally this should be formatted similar to the
table created with trace_through_me_by_hand, but do not worry too much about how the prints format the
output.
10.3. Algorithm
Functions like
trace_through_me_by_handandint_sumare examples of algorithmsAn algorithm is a description of steps one could take to solve a given problem
Driving directions and cookie recipes are algorithms
Although algorithms can be explained in a natural language like English, when programming we write our algorithms in code
Finding an algorithm for a problem takes practice
You can make a career out of coming up with algorithms
Activity
Write down (in English) an algorithm for calculating the sum of all the even numbers between
0andn.Convert the algorithm into a Python function
sum_even_numbers(n: int) -> int.Write some
asserttests to verify correctness.