
Python
While loops are perfect when you don't know exactly how many times you need to repeat, but you know when to stop.
while condition:
# code to repeat
# condition will become False to exit loopcount = 0
while count < 5:
print(f"Count: {count}")
count = count + 1
# Output: 0, 1, 2, 3, 4Important: You must change the variable so the loop eventually stops!
Example 1: User input validation
age = -1
while age < 0:
age = int(input("Enter your age (must be positive): "))
if age < 0:
print("Age must be positive!")Example 2: Guessing game
number = 42
guess = -1
while guess != number:
guess = int(input("Guess the number: "))
if guess < number:
print("Too low!")
elif guess > number:
print("Too high!")
print("Correct!")Example 3: Countdown
countdown = 5
while countdown > 0:
print(countdown)
countdown = countdown - 1
print("Blastoff!")# ❌ INFINITE LOOP - never changes x, so x < 5 is always True
x = 0
while x < 5:
print(x)
# Missing: x = x + 1
# ✅ CORRECT - x increases each loop
x = 0
while x < 5:
print(x)
x = x + 1| When | Loop Type | Example |
|---|---|---|
| Know exact count | For loop | `for i in range(5):` |
| Unknown iterations | While loop | `while user_wants_more:` |
| Processing list | For loop | `for item in list:` |
| User input validation | While loop | `while not valid:` |
| Concept | Remember |
|---|---|
| Condition | Must eventually become False |
| Update Variable | Change something in the loop |
| Infinite Loops | Avoid loops that never end |
| When to Use | Unknown number of iterations |
Control your loops with Loop Control (Break & Continue)!
Ready to practice? Challenges | Quiz
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep • Build Real • Verify Skills • Launch Forward