Skip to content

Sep 25: Quiz2, for Statements

Learning Objectives

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

  • Explain the syntax and meaning of a for statement.
  • Describe examples of how a for loop can be used.

Reminders

  • Due today: HW5 Reflection
  • Read Ch 6 – ideally:
    • 1st half before Friday
    • 2nd half before Monday
  • Submit HW 6 – ideally:
    • 1 and 2 before Friday
    • 3 and 4 before Monday

HW5 Debrief

  • Identity vs equality (is vs ==)
  • Helper functions (Ex: swap())
  • Passing containers to functions
    • If immutable, return new object
    • If mutable, edit existing object
  • Returning "fairness" of two sets
The Unofficial Graduation Requirement for CS/IT Majors

Students who write code like this will not be allowed to graduate:

if condition:
    return True
else:
    return False

The above code should be written without using an if statement:

return condition

Quiz 2

  • Log in as student
  • Only two windows:
    1. Thonny
    2. Web browser
  • Web traffic monitored
  • Log out when finished

Ch06 Preview

  • The "for each" loop
    • Syntax: for variable in iterable
    • Meaning: repeat the following code
  • Run examples in Python Tutor
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 = {"laundry", "vacuuming", "dishes", "raking", "shopping"}
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

Notice that the upper bound (7) is not in the range.

print("1 bottle of pop")
for number in range(2, 7):
    print(number, "bottles of pop")
print("7, 7, bottles of pop!")
Example 5: for each key in a dictionary
month_days = {
    "January": 31,
    "February": 28,  # 29 in a leap year
    "March": 31,
    "April": 30,
    "May": 31,
    "June": 30,
    "July": 31,
    "August": 31,
    "September": 30,
    "October": 31,
    "November": 30,
    "December": 31,
}

for key in month_days:
    value = month_days[key]
    print(f"{key} has {value} days")
Example 6: for each key-value pair in a dictionary

Notice how the dictionary's items() method is called.

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():
    print(f"Today is {day}, today is {day}.")
    print(f"{day} {food}.")
    print("All you hungry children, come and eat it up!")
    print()