Skip to content

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

  • Due tomorrow
  • Practice quiz 3 on Thursday

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

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 Sep30 assignment on Runestone
  • If you are absent, do this on your own

Next Topic: For loops

Introduction to 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")
Example 2: for each value in a set
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)
Example 3: for each character in a string
message = "Please help!"
for c in message:
    if c not in ['a', 'e', 'i', 'o', 'u']:
        print(c, end="")
print()
Example 4: for each integer in a range
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?
Example 5: for each key in a dictionary
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()