Sep 30: Solving Problems with Loops
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
- Trace for loops and their use with containers
- Usage of range and enumerate with for statements
Reminders¶
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 with Loops¶
Exercises 10 min
- For each while loop:
- Predict the output/behavior by hand on paper.
- Check your answer using Thonny's debugger.
E-1¶
count = 1
while count <= 3:
count += 1
print(count)
E-2¶
count = 7
while count > 3:
print(count)
count -= 2
E-3¶
count = 1
while count <= 6:
if count % 2 == 0:
count += 3
else:
count += 1
print(count)
E-4¶
count = 1
while count < 10 and count % 7 != 0:
print(count)
count += 1
E-5¶
count = 10
while count > 0:
count += 1
print(count)
E-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:breakandcontinuePython Tutorial 4.4- Walrus operator
:=Python Reference 6.12
Classic while True
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.")
Activity for today
- Complete the
Sep30assignment on Runestone - If you are absent, do this on your own
Next Topic: For loops¶
Run in PythonTutor
Example 1: for each element of a list
words = ["Pause", "brink", "fox", "Cup", "match", "sound",
"president", "Restless", "despise", "Rack"]
for word in words:
if word[0].isupper():
print(word, "is capitalized")
tasks = set()
tasks = {"laundry", "vacuuming", "dishes", "raking", "shopping"}
for t in tasks:
print("You need to do the", t)
tasks.add("sleeping")
print("New tasks")
for t in tasks:
print("You need to do the", t)
message = "Please help!"
for c in message:
if c not in ['a', 'e', 'i', 'o', 'u']:
print(c, end="")
print()
print("1 bottle of pop")
for number in range(2, 7):
print(number, "bottles of pop")
print("7, 7, bottles of pop!") # why this line?
verses = {
"Monday": "string beans",
"Tuesday": "spaghetti",
"Wednesday": "soup",
"Thursday": "roast beef",
"Friday": "fresh fish",
"Saturday": "chicken",
"Sunday": "ice-cream",
}
for day, food in verses.items(): # notice items()
print(f"Today is {day}, today is {day}.")
print(f"{day} {food}.")
print("All you hungry children, come and eat it up!")
print()