Lesson 10 of 12
While Loops ⏳
What You'll Learn
- Use while loops for unknown repetitions
- Avoid infinite loops
- Build a number guessing game
While vs For
A for loop is great when you know exactly how many times to repeat. A while loop keeps running as long as a condition stays True — useful when you do not know in advance how many times you need to loop.
Python
# Keep asking until a valid answer
password = ''
while password != 'opensesame':
password = input('Enter the password: ')
print('Access granted!')Counting with While
Python
count = 1
while count <= 5:
print(f'Count: {count}')
count += 1 # IMPORTANT: increment or loop runs forever!
print('Done!')Avoid Infinite Loops
Always make sure your while condition will eventually become False. If it never does, your program runs forever and freezes!
Guessing Game!
Pick a secret number (assign it to a variable). Use a while loop to keep asking the user to guess. Tell them Higher or Lower after each guess. Print how many tries it took!
Quick Check
When does a while loop stop?
Why must you update the variable inside a while loop?
Which loop is better when you do not know the number of iterations?