Sep 29: Tracing Loops by Hand
Learning Objectives
After today's class, you should be able to:
- Trace the execution of loops that change variables.
- Predict the output of code segments having a loop.
- Use a loop to build a container of selected results.
Reminders¶
- Due tomorrow
- Practice Quiz 3 on Wednesday
Containers Review¶
Note: The following table is not exhaustive. But these details can be useful to memorize.
Name | Create empty | Operators | Important methods |
---|---|---|---|
List | [] or list() |
[i] , in , + , * |
append, count, index, insert, pop, remove |
Tuple | () or tuple() |
[i] , in , + , * |
count, index |
Set | set() only |
in |
add, pop, remove |
Dict | {} or dict() |
[k] , in |
get, items, pop |
Tracing while
loops¶
Exercise 1 (10 min)
For each while
loop:
- Predict the output/behavior by hand on paper.
- Check your answer using Thonny's debugger.
W-1
count = 1
while count <= 3:
count += 1
print(count)
W-2
count = 7
while count > 3:
print(count)
count -= 2
W-3
count = 1
while count <= 6:
if count % 2 == 0:
count += 3
else:
count += 1
print(count)
W-4
count = 1
while count < 10 and count % 7 != 0:
print(count)
count += 1
W-5
count = 10
while count > 0:
count += 1
print(count)
W-6
grades = [93, 82, 67, 99]
while len(grades) > 1:
min_grade = min(grades)
print(min_grade)
grades.remove(min_grade)
Infinite Loops¶
- On accident – condition is always true
- Gradescope times out after 5 seconds
- On purpose –
while True:
break
andcontinue
– Python Tutorial 4.4- Walrus operator
:=
– Python Reference 6.12
Classic while True
loop
Straightforward, but uses break
:
while True:
num = int(input("Positive integer: "))
if num > 0:
break
print("Invalid input, try again.")
Using the walrus operator
More concise, but harder to read:
# The previous example had the opposite condition
while num := int(input("Positive integer: ")) <= 0:
print("Invalid input, try again.")
More Practice¶
- Complete the
Sep29
assignment on Runestone- If you are absent today, do this on your own