Skip to content

While vs For Loops

Provided Files

Example Code

Model 1

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

Question 9

total_count.py
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 2

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