Skip to content

Oct 06: While Loops and Random

Learning Objectives

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

  • Identify the three main components of a while loop.
  • Use the random module to generate random numbers.
  • Explain when to use a while loop versus a for loop.

Announcements

  • Homework
  • Quiz 3a scores are on Gradescope
    • I'll wait until next week to import into Canvas
    • Please see Canvas Files, rework the problem
    • Ask for help if you can't figure out a solution

POGIL Activity

  • While Loops
    • If you are absent today, complete this activity at home
    • Bring your completed activity to class or office hours

Example Code

Model 1

i = 0
while i < 3:
    print("the number is", i)
    i = i + 1
print("goodbye")

Question 9

total_count.py
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
total = 0
count = 0

n = None
while n != 0:
    n = float(input("Next number: "))
    total += n
    count += 1

print()
print("Total:", total)
print("Count:", count)

Model 3

guess_number.py
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
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!")
coin_toss.py
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
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}%")