Skip to content

Oct 20: Prac4; 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

Due tomorrow:

For vs While Loops

[10 min]

  • coin_toss.pyfor loop
    • Rewrite using a while loop
  • guess_number.pywhile loop
    • Rewrite using a for loop
  • When to use for instead of while
    • 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
  • Purpose of if __name__ == "__main__":

move.py
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
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
1
2
3
4
import move

print("in stop: __name__ ==", __name__)
print("from module: angle ==", move.angle())

Practice Quiz 4

[15 min]

  • Written during class
  • Coding outside class