while loop
A while loop is used to repeat a block of code as long as a condition is True.
- Useful when we do not know how many times the loop will run
- The loop continues until the condition becomes
False - It uses a condition to control execution
- Variables inside the loop must be updated
- If not handled properly, it can create an
infinite loop
Explanation
- First, the condition is checked
- If True → code runs
- Then the condition is checked again
- This repeats until condition becomes False
Real-Life Scenario
- Enter password until it is correct
- Playing a game until lives become 0
- Filling water until the tank is full
Loop runs until the condition becomes False
Syntax
while condition:
# code
Example 1
i = 1
while i <= 3:
print("Hi")
i += 1
Output
Hi
Hi
Hi
Example 2
num = 1
sum = 0
while num <= 5:
sum += num
num += 1
print(sum)
Output
15
Explanation of Example
- Loop runs from 1 to 5
- Adds values → 1+2+3+4+5 = 15
Why while loop is Important
- Used when repetitions are unknown
- Helps in real-world tasks like validation
- Useful in games and user input programs
- Builds logical thinking
Difference Between for Loop and while Loop
| Feature | for Loop | while Loop |
|---|---|---|
| Use | Fixed repetitions | Condition-based |
| Easy | Easy | Medium |
| Risk | Less | Can cause infinite loop |
Common Beginner Mistakes
- Forgetting to update variable
- Creating infinite loop
- Wrong condition
- Incorrect indentation
➤ Key Points
while loopruns until condition becomes False- Depends on a True/False condition
- Number of repetitions is not fixed
- Needs variable update
- Can cause infinite loop if not handled
➤ Tips
- Use while loop when repetitions are unknown
- Always update variable (i += 1)
- Check condition carefully
- Avoid infinite loops
- Good for user input, games, validations
- Test with small values first