September 28: Loops

Learning Objectives

After today's class, you should be able to:

  • Understand the structure of for loops and iterating over a sequence
  • Implement for loops interating a list
  • Use a range object with a for loop

Lesson Outline

Quiz 2B: 25 minutes

  • Log in as student on the lab machine
  • Open web browser, go to canvas and log in with your eid
  • In canvas, go to Modules, Quiz2B
  • Do part one of the Module
  • The programming portion is given on sheet of paper
  • Open Thonny
  • Submit work using Canvas with Gradesope, Module Quiz2, Programming

Mini Lecture: Chapter Introduction and activities

Run each of the following 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()

Inclass Activity

Your To-Do List

By today

Complete by Monday October 2nd

Due Wednesday October 4th at 11pm