► Overview
A while loop repeats code as long as a condition remains true. Unlike for loops that iterate over sequences, while loops continue until their condition becomes false. They’re perfect for situations where you don’t know exactly how many times to repeat.
► Real-World Analogy
Think of filling a water bottle:
» While bottle is not full
» Keep adding water
» Check if full
» Stop when full
► Key Concepts
✓ Condition: Boolean expression checked before each iteration
✓ Continues while condition is True
✓ Must update condition inside loop to avoid infinite loops
✓ Common for unknown iteration counts
✓ Can be infinite if condition never becomes False
■ While Loop Examples
/code
Basic while loop
count = 0
while count < 5:
print(“Count is:”, count)
count += 1
User input validation
password = “”
while password != “secret”:
password = input(“Enter password: “)
if password != “secret”:
print(“Wrong password, try again”)
Sum until target
total = 0
number = 1
while total < 50:
total += number
number += 1
print(“Total:”, total)
Output:
Count is: 0
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Enter password: hello
Wrong password, try again
Enter password: secret
Total: 55
► Important Points
✓ Always update the condition variable inside the loop
✓ Test your condition to avoid infinite loops
✓ While loops are great for validation and user input
✓ Can use break to exit loop early
✓ More flexible than for loops for unknown iterations
► Remember
✓ Ensure the loop condition eventually becomes False
✓ Initialize variables before the while loop
✓ Increment/update inside the loop body
✓ Use for loops when you know iteration count
■ Practice Challenge
- Create a while loop that prints even numbers from 2 to 20
- Write a number guessing game using while loop
- Calculate factorial using while loop
