Skip to content

Oct 09: Tracing Iteration 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
  • Quiz 3b on Wednesday

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)

Tracing for loops

Exercise 2  (10 min)

For each for loop:

  • Predict the output/behavior by hand on paper.
  • Check your answer using Thonny's debugger.

F-1

for row in range(10):
    print(row, end="\t")
    print("#" * row)

F-2

cities = ["boise", "omaha", "tulsa", "utica"]
result = []
for city in cities:
    result.append(city.upper())
print(result)

F-3

word = "onomatopoeia"
locs = []
for i in range(len(word)):
    if word[i] in ('a', 'e', 'i', 'o', 'u'):
        locs.append(i)
print("Locations:", locs)

F-4

count = 0
prev = 0
words = ["Book", "Car", "City", "Dog", "Enough", "Friend", "House"]
for w in words:
    if len(w) < prev:
        count += 1
    prev = len(w)
print("Count is", count)

F-5

name = "James Madison University"
words = name.split()
acronym = ""
for word in words:
    letter = word[0]
    print(letter, "is for", word)
    acronym += letter
print(acronym)

F-6

index = None
word = "Mississippi"
for i in range(len(word)-1):
    if word[i] == word[i+1]:
        index = i
print("Index is", index)

Review containers

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

Exercise 3  (10 min)

Write a function named get_short(words) that takes a list of words and returns the words that have at most 5 letters. Do not change the list you are given. Instead, follow these steps:

  1. Create an empty list.
  2. Write a for loop that adds one word at a time to the list.
  3. Return the resulting list. (At the end, not in the loop!)

Repeat the exercise using set and dict as the return type. For dict, use the word for the key and the length for the value.

Exercise 4  (10 min)

Write a function named five_star(hotels) that takes a dictionary of hotel names and ratings. Return a list of hotels that have a rating of 4.5 or higher. Ex: Given {"Ritz": 5.0, "Marriott": 4.5, "Madison": 4.2}, return ["Ritz", "Marriott"].

Repeat the exercise using a list of tuples as the input. Ex: [("Ritz", 5.0), ("Marriott", 4.5), ("Madison", 4.2)].