A while loop helps repeat actions as long as something is true. It saves time and avoids writing the same code again and again.
Why while loop is needed in Python
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Python
while condition: # code to repeat # update condition or break
The condition is checked before each repeat.
If the condition is false at the start, the code inside the loop won't run at all.
Examples
Python
count = 3 while count > 0: print(count) count -= 1
Python
answer = '' while answer != 'yes': answer = input('Type yes to continue: ')
Sample Program
This program counts down from 5 to 1 and then prints 'Done!'. It shows how while repeats until the count reaches zero.
Python
count = 5 while count > 0: print(f'Counting down: {count}') count -= 1 print('Done!')
Important Notes
Always make sure the condition will become false at some point, or the loop will run forever.
You can use break inside a while loop to stop it early.
Summary
While loops repeat code as long as a condition is true.
They are useful when you don't know how many times to repeat before starting.
Make sure the loop will stop eventually to avoid infinite loops.
Practice
1. Why do we use a
while loop in Python instead of a for loop?easy
Solution
Step 1: Understand the difference between
whileandforloopsforloops run a fixed number of times, whilewhileloops run as long as a condition is true.Step 2: Identify when
whileloops are neededwhileloops are useful when the number of repetitions is unknown before starting.Final Answer:
Because we don't always know how many times the loop should run before starting. -> Option BQuick Check:
Unknown repetitions = usewhileloop [OK]
Hint: Use while when repeat count is unknown before start [OK]
Common Mistakes:
- Thinking for loops can handle unknown repetitions
- Believing while loops don't need conditions
- Confusing speed differences between loops
2. Which of the following is the correct syntax to start a
while loop in Python?easy
Solution
Step 1: Recall Python's
Python requires a colon (:) after the condition and indentation for the loop body.whileloop syntaxStep 2: Check each option
while x > 0: print(x) uses colon and correct indentation style (single line allowed). Others have syntax errors.Final Answer:
while x > 0: print(x) -> Option AQuick Check:
Colon after condition = correct syntax [OK]
Hint: Remember colon (:) after condition in while loops [OK]
Common Mistakes:
- Missing colon after condition
- Using braces {} like other languages
- Incorrect print statement syntax
3. What will be the output of this code?
count = 3
while count > 0:
print(count)
count -= 1
print('Done')medium
Solution
Step 1: Trace the loop iterations
count starts at 3, prints 3, then decreases to 2, prints 2, then 1, prints 1, then count becomes 0 and loop stops.Step 2: Check what prints after loop
After loop ends, 'Done' is printed.Final Answer:
3 2 1 Done -> Option CQuick Check:
Loop prints 3 to 1, then 'Done' [OK]
Hint: Count down loop prints values until condition false [OK]
Common Mistakes:
- Expecting 0 to print inside loop
- Missing 'Done' print after loop
- Confusing loop stop condition
4. Find the error in this code snippet:
i = 1
while i < 5:
print(i)
i += 1medium
Solution
Step 1: Check indentation of loop body
Python requires the code inside the while loop to be indented equally. Here,print(i)is not indented properly.Step 2: Verify other parts
Colon is present, variable i is initialized, and i increments, so no infinite loop.Final Answer:
Indentation error inside the loop -> Option AQuick Check:
Loop body must be indented [OK]
Hint: Indent all loop lines equally to avoid errors [OK]
Common Mistakes:
- Not indenting loop body
- Forgetting colon after while
- Assuming variable needs declaration
5. You want to keep asking a user for a password until they enter the correct one. Which code snippet correctly uses a
while loop for this?hard
Solution
Step 1: Understand the goal
We want to keep asking until the user types 'secret'. This requires input inside the loop and proper exit condition.Step 2: Analyze each option
password = ''\nwhile password != 'secret':\n password = input('Enter password: ') print('Access granted') initializes empty password, checks condition, inputs inside loop, updates, and exits when equal to 'secret'.
while true:\n password = input('Enter password: ') if password == 'secret':\n break print('Access granted') uses 'true' which is undefined in Python (must be 'True'), causing NameError.
for password in ['secret']:\n input('Enter password: ') print('Access granted') uses for loop incorrectly, runs fixed once without checking input.
password = input('Enter password: ') while password == 'secret': print('Access granted') inputs once then loops only if correct, fails to re-ask on wrong.Final Answer:
password = ''\nwhile password != 'secret':\n password = input('Enter password: ') print('Access granted') -> Option DQuick Check:
While != condition + input inside = repeat until match [OK]
Hint: While != target: input() inside loop [OK]
Common Mistakes:
- Using 'true' instead of 'True'
- Using for loop for unknown repeats
- Wrong condition (== instead of !=)
