While Loops
Iteration lets programs repeat actions. In Python, while loops are condition controlled: the loop continues as long as the condition is True.
Simple while loop
This loop starts at 1 and increments until it exceeds 10:
number = 1
while number <= 10:
print(number)
number = number + 1
Task 1 – Countdown from 100
Create a while loop that prints each number from 100 down to 1:
number = 100
while number >= 1:
print(number)
number = number - 1
Inputs inside while loops
Use input inside the loop until a condition is met:
month = ""
while month != "July":
month = input("Guess the month I'm thinking of: ")
print("Correct! It was July!")
Task 2 – Guess the colour
colour = ""
while colour.lower() != "yellow":
colour = input("Guess the colour: ")
print("Correct! It was yellow!")
Task 3 – Integer trivia
correct_answer = 2008
year = 0
while year != correct_answer:
year = int(input("Which year was the first Iron Man movie? "))
print("Correct! It was", correct_answer)
while True loops
A while True loop repeats indefinitely until you break:
while True:
password = input("Enter the password: ")
if password == "icecream21":
print("Correct Password!")
break
Counting attempts with while True
guesses = 0
while True:
guesses += 1
password = input("Enter the password: ")
if password == "goat7":
print("Correct Password! It took", guesses, "attempts!")
break
else:
print("Incorrect. Try again!")
Using continue
Skip to the next iteration with continue:
total = 0
while True:
choice = input("Type 1 to enter, 2 for total, and 3 to stop: ")
if choice == "1":
number = int(input("Enter a number: "))
total += number
continue
elif choice == "2":
print("The total is", total)
continue
elif choice == "3":
break
print("Program finished.")
Task 4 – Guess the planet
guesses = 0
while True:
guesses += 1
planet = input("Enter a planet: ")
if planet.lower() == "neptune":
print("Correct! It was Neptune!")
print("It took", guesses, "attempts.")
break
else:
print("Incorrect guess, try again!")
Task 5 – Up to 100
Keep adding numbers until the total reaches 100 or more:
total = 0
while True:
number = int(input("Enter a number: "))
total += number
print("The current total is:", total)
if total >= 100:
print("Over 100!")
break
Tips:
- Always update the variable inside the loop or you risk an infinite loop.
- Use
breakto exit early; usecontinueto skip to the next iteration.