Oct 21: Practice quiz 4; Loops and Modules
Learning Objectives
After today's class, you should be able to:
- Explain when to use a for loop versus a while loop.
- Predict the output of code segments with a for loop.
- Explain the purpose of if name == "main".
Announcements¶
- Project 1, due tonight
- Today is the last day to drop the course. Recall a B- is required to take to CS159 and only two attempts are allowed for CS149
Practice Quiz 4¶
- Two portions to the quiz: written and coding
- Log in as
student - Start exam recording
- Log in to Canvas only
- Raise your hand when complete with Canvas written portion
- Open Thonny for coding portion only
- Submit code through Canvas (will go to Gradescope)
- Log out when finished
For vs While loops¶
Exercise
Rewrite the following:
Rewrite coin_toss.py using a while loop
"""Simulate tossing a coin one million times."""
import random
heads = 0
tails = 0
times = 1000000
for _ in range(times):
if random.random() < 0.5:
heads += 1
else:
tails += 1
heads = round(heads / times * 100, 2)
tails = round(tails / times * 100, 2)
print(f"Head: {heads}%, Tail: {tails}%")
guess_numbers.py using a for loop
"""Play a random number guessing game."""
import random
print("Guess my number!")
number = random.randint(1, 100)
guess = 0
while guess != number:
guess = int(input("Guess: "))
if guess > number:
print("Too high!")
elif guess < number:
print("Too low!")
print("You got it!")
Tracing For Loops¶
For each for loop:
- Predict the output/behavior by hand on paper.
- Check your answer using Thonny's debugger.
For-1¶
for row in range(10):
print(row, end="\t")
print("#" * row)
For-2¶
cities = ["boise", "omaha", "tulsa", "utica"]
result = []
for city in cities:
result.append(city.upper())
print(result)
For-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)
For-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)
For-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)
For-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¶
- Value of the built-in variable
__name__- When running move.py
- When running stop.py
- Purpose of if
__name__ == "__main__":
move.py
import random
def angle():
number = random.randint(-90, 90)
return number
print("in move: __name__ ==", __name__)
print("will always execute: angle ==", angle())
if __name__ == "__main__":
print("only if True: angle ==", angle())
stop.py
import move
print("in stop: __name__ ==", __name__)
print("from module: angle ==", move.angle())