Skip to content

Oct 04: 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.

Reminders

  • Read Ch 7 – ideally:
    • 1st half before Friday
    • 2nd half before Monday
  • Submit HW 7 – ideally:
    • 1 and 2 before Friday
    • 3 and 4 before Monday

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}%")