- What the while loop is ā understanding condition-based repetition
- Syntax and structure ā writing proper while loops
- Flowchart and execution ā how Python processes while loops
- Infinite loops ā how they happen and how to avoid them
- Else clause ā using else with while loops
- Break and continue ā controlling loop execution
- Real-world examples ā practical applications of while loops
- Hands-on practice with the interactive editor
What is a While Loop?
A while loop in Python repeatedly executes a block of code as long as a given condition is True. It's a fundamental control flow tool that allows you to automate repetitive tasks where the number of iterations isn't known in advance.
Key insight: The while loop is perfect when you don't know how many times you need to repeat ā it keeps going until a condition changes. It's like saying, "Keep doing this while something is true."
Think of a while loop like waiting for a bus. You check the condition ("Is the bus here?"). If false, you wait (repeat the loop). Once true, you stop waiting and get on the bus. The loop continues until the condition becomes false.
While Loop Syntax
The syntax of a while loop is simple and intuitive:
# Syntax
while condition:
# Code to repeat (the loop body)
# This runs as long as condition is True
# Example
count = 1
while count <= 5:
print(f"Count is: {count}")
count += 1
# Output:
# Count is: 1
# Count is: 2
# Count is: 3
# Count is: 4
# Count is: 5
š Important: The condition is checked before each iteration. If it's True, the loop body executes. If False, the loop ends. This is called a "pre-test" loop because the condition is tested before the code runs.
Key points to remember:
- The condition must eventually become
Falseto avoid an infinite loop - You must change the condition inside the loop (like incrementing a counter)
- The loop body must be indented (usually 4 spaces)
- You can use any expression that evaluates to
TrueorFalse
Flowchart & Execution Flow
Understanding the flow of a while loop helps you write correct code. Here's how Python executes a while loop:
Step-by-step execution:
- Python evaluates the condition
- If
True, it executes the loop body and goes back to step 1 - If
False, it skips the loop body and continues with the code after the loop
While Loop Examples
Let's explore different examples of the while loop in action:
# Example 1: Count from 1 to 10
num = 1
while num <= 10:
print(num, end=" ")
num += 1
# Output: 1 2 3 4 5 6 7 8 9 10
# Example 2: Sum of numbers from 1 to 100
total = 0
i = 1
while i <= 100:
total += i
i += 1
print(f"\nSum of 1 to 100: {total}")
# Output: Sum of 1 to 100: 5050
# Example 3: Print even numbers
num = 2
while num <= 20:
print(num, end=" ")
num += 2
# Output: 2 4 6 8 10 12 14 16 18 20
# Example 4: Countdown timer
countdown = 5
while countdown > 0:
print(f" {countdown}")
countdown -= 1
print(" Liftoff!")
# Output:
# 5
# 4
# 3
# 2
# 1
# Liftoff!
Infinite While Loops
An infinite loop is a loop that never ends because its condition never becomes False. While this can be useful in some cases (like game loops or server programs), it's usually a bug that freezes your program.
# INFINITE LOOP - DON'T RUN!
# This will run forever
while True:
print("This never stops!")
# Another infinite loop
count = 1
while count < 10:
# Forgot to increment count!
print(count) # This prints 1 forever
# BAD: The condition never changes
x = 5
while x > 0:
print(x)
# Missing: x -= 1
Warning: Always ensure your loop condition will eventually become False. Common mistakes include forgetting to update the variable that controls the condition or using the wrong condition.
How to stop an infinite loop:
- Press Ctrl+C (or Cmd+C on Mac) in the terminal
- Close the terminal/IDE window
- Use a debugger to pause execution
Else Clause with While
Python allows an else clause with while loops. The else block runs when the loop condition becomes False normally (not when broken).
# Example: else with while
num = 1
while num <= 3:
print(f"Number: {num}")
num += 1
else:
print("Loop completed normally!")
# Output:
# Number: 1
# Number: 2
# Number: 3
# Loop completed normally!
# With break - else doesn't run
num = 1
while num <= 5:
if num == 3:
break
print(num)
num += 1
else:
print("This won't run because of break")
# Output: 1 2
š Use case: The else clause is useful for checking if a loop was completed or broken. It's often used in search algorithms to indicate if an item was found.
Break and Continue in While Loops
Just like for loops, while loops support break and continue statements:
# break - exits the loop
num = 1
while num <= 10:
if num == 5:
break
print(num, end=" ")
num += 1
# Output: 1 2 3 4
# continue - skips current iteration
num = 0
while num < 5:
num += 1
if num == 3:
continue
print(num, end=" ")
# Output: 1 2 4 5
# Using break with user input
while True:
user_input = input("Type 'quit' to exit: ")
if user_input.lower() == 'quit':
break
print(f"You typed: {user_input}")
Real-World Use Cases
š” Use Case 1: User Input Validation
# Keep asking until user enters a valid number
valid_input = False
while not valid_input:
try:
age = int(input("Enter your age: "))
if age > 0 and age < 120:
valid_input = True
print(f"Your age is: {age}")
else:
print("Please enter a valid age (1-119)")
except ValueError:
print("Invalid input! Please enter a number.")
š” Use Case 2: ATM or Banking System
# Simple ATM simulation
balance = 1000
pin = "1234"
attempts = 3
while attempts > 0:
entered_pin = input("Enter your PIN: ")
if entered_pin == pin:
print("ā
PIN correct!")
while True:
print(f"\nBalance: ā¹{balance}")
print("1. Withdraw")
print("2. Deposit")
print("3. Exit")
choice = input("Choose option: ")
if choice == "1":
amount = float(input("Amount to withdraw: "))
if amount <= balance:
balance -= amount
print(f"ā¹{amount} withdrawn. New balance: ā¹{balance}")
else:
print("Insufficient balance!")
elif choice == "2":
amount = float(input("Amount to deposit: "))
balance += amount
print(f"ā¹{amount} deposited. New balance: ā¹{balance}")
elif choice == "3":
print("Thank you for banking!")
break
break
else:
attempts -= 1
print(f"ā Wrong PIN. {attempts} attempts remaining.")
else:
print("š Account locked due to too many failed attempts.")
š” Use Case 3: Game Loop
# Simple guessing game
import random
secret_number = random.randint(1, 10)
guess = None
attempts = 0
print("šÆ Guess the number (1-10)!")
while guess != secret_number:
try:
guess = int(input("Your guess: "))
attempts += 1
if guess < secret_number:
print("š Too low!")
elif guess > secret_number:
print("š Too high!")
else:
print(f"š Correct! You got it in {attempts} attempts!")
except ValueError:
print("ā Please enter a valid number!")
Try It Yourself!
Experiment with while loops directly in your browser. Modify the code and see the results in real time.
WHILE LOOP DEMONSTRATION
========================================
1. BASIC WHILE LOOP
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
2. SUM OF NUMBERS
Sum of 1 to 10: 55
3. BREAK STATEMENT
1 2 3 4
4. CONTINUE STATEMENT
1 2 4 5
5. ELSE CLAUSE
1 2 3
Loop completed!
ā Explore the while loop!
š You've Learned Python While Loops!
You understand while loop syntax, infinite loops, else clause, break, continue, and real-world applications. These are essential for writing dynamic Python programs!
Quick Quiz ā Test Your Knowledge
Let's see what you've learned about while loops:
else clause in a while loop execute?continue statement do in a while loop?Frequently Asked Questions
š¤ What's the difference between a while loop and a for loop?
š§ Can I use break and continue in the same while loop?
break and continue can be used in the same while loop. break exits the loop completely, while continue skips the rest of the current iteration and moves to the next condition check.
š How do I avoid infinite loops?
False, (3) Use break when needed, and (4) Test your loop with small numbers first to verify it works correctly.
š Can I use a while loop with user input?
ā” Is there a performance difference between while and for loops?
for loops are slightly faster in Python because the iteration mechanism is optimized in C. However, the performance difference is minimal for most applications. Choose the loop that makes your code more readable and appropriate for the task.
šÆ Can I nest while loops inside each other?
š Where to Go From Here
Now that you've mastered the while loop, here are the next topics to explore:
š Nested While Loop
Learn how to use while loops inside other while loops.
Learn More āš The for Loop
Master the for loop and compare it with while loops.
Learn More āš While Loop Assignments
Practice what you've learned with coding challenges.
Practice ā