Ojasa Mirai

Ojasa Mirai

Python

Loading...

Learning Level

🟢 Beginner🔵 Advanced
Why Loops?For Loops BasicsWhile Loops BasicsLoop ControlIterating ListsLoop PatternsNested LoopsDebugging LoopsBest Practices
Python/Loops/While Loops Basics

⚡ While Loops Basics — Repeat Until a Condition is Met

While loops are perfect when you don't know exactly how many times you need to repeat, but you know when to stop.


🎯 While Loop Syntax

while condition:
    # code to repeat
    # condition will become False to exit loop

💡 Basic Example

count = 0
while count < 5:
    print(f"Count: {count}")
    count = count + 1
# Output: 0, 1, 2, 3, 4

Important: You must change the variable so the loop eventually stops!


🎨 Practical Examples

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!")

⚠️ Common Mistake: Infinite Loops

# ❌ 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

📊 For vs While

WhenLoop TypeExample
Know exact countFor loop`for i in range(5):`
Unknown iterationsWhile loop`while user_wants_more:`
Processing listFor loop`for item in list:`
User input validationWhile loop`while not valid:`

🔑 Key Takeaways

ConceptRemember
ConditionMust eventually become False
Update VariableChange something in the loop
Infinite LoopsAvoid loops that never end
When to UseUnknown number of iterations

🔗 What's Next?

Control your loops with Loop Control (Break & Continue)!


Ready to practice? Challenges | Quiz


Resources

Python Docs

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

Courses

PythonFastapiReactJSCloud

© 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn