Oct 20: Prac4; Loops and Modules
Learning Objectives
After today's class, you should be able to:
- Explain when to use a
forloop versus awhileloop. - Predict the output of code segments with a
forloop. - Explain the purpose of
if __name__ == "__main__".
Announcements¶
Due tomorrow:
- Reading Week 9
- Part B of PA 1
- PA1 Reflection
For vs While Loops¶
[10 min]
- coin_toss.py →
forloop- Rewrite using a
whileloop
- Rewrite using a
- guess_number.py →
whileloop- Rewrite using a
forloop
- Rewrite using a
- When to use
forinstead ofwhile- Hint: over 75% of the time
Tracing For Loops¶
[15 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)
Tracing Modules¶
[10 min]
- Difference between a script and a module
- Importing a module from the same folder
- The
__pycache__folder (auto generated)
- Value of the built-in variable
__name__- When running
move.py - When running
stop.py
- When running
- Purpose of
if __name__ == "__main__":
| move.py | |
|---|---|
1 2 3 4 5 6 7 8 9 10 11 | |
| stop.py | |
|---|---|
1 2 3 4 | |
Practice Quiz 4¶
[15 min]
- Written during class
- Coding outside class