While Loops
3 min read ·
A
while loop is used to execute a block of code repeatedly as long as a given condition is True.Python keeps checking the condition:
- If condition is
True→ loop runs - If condition becomes
False→ loop stops
Why Use a while Loop?
Use a
while loop when:- You do not know in advance how many times the loop should run
- The loop depends on a condition
- Repetition is required until a condition changes
Basic Idea of while Loop
whileis a keyword- Condition must return
TrueorFalse - Indentation defines the loop body
Note
If the condition never becomes False, the loop will run forever.
Simple Example of while Loop
- Loop starts with
i = 1 - Condition:
i <= 5 - Value of
ichanges every iteration
Flow of while Loop Execution
- Condition is checked
- If condition is True → code runs
- Variable is updated
- Condition is checked again
This continues until the condition becomes False.
while Loop with Condition
while Loop with Boolean Condition
while Loop with User Input
Infinite while Loop
Caution
Always make sure the condition can become False.
Common Mistake in while Loop
Missing Update Statement ❌
This creates an infinite loop.
Stop
Forgetting to update the loop variable is the most common while loop error.
Real World Example
Real World Scenario
ATM keeps running until the user exits
Exercise
Practice Task
- Print numbers from 1 to 10 using
whileloop - Print numbers in reverse order
- Create a loop that runs until user enters 0
- Observe what happens if condition never changes