Oct 01: Prac3, 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: HW6 Reflection
- Read Week 7 – ideally:
- 1st half before Friday
- 2nd half before Monday
- Submit HW 7 – ideally:
- 1 and 2 before Friday
- 3 and 4 before Monday
HW6 Debrief¶
- Testing with
doctest
– Real Python tutorial random.randint()
versusrandom.random()
if
-elif
-else
inside of awhile
loop- Importing functions from another module
Practice Quiz 3¶
- 1st sheet: "written portion"
- 2nd sheet: "coding portion" (write code on paper)
Wk07 Preview¶
- The "for each" loop
- Syntax:
for
variablein
iterable - Meaning: repeat the following code
- Syntax:
- 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()