</>
Skip to content
Python lessons (19/45)

Python — While Loops

Basic While Loop

count = 0
while count < 5:
    print(count)
    count += 1
# 0, 1, 2, 3, 4

How While Loops Work

  1. Check the condition
  2. If True, execute the body
  3. Go back to step 1
  4. If False, exit the loop
# Infinite loop (be careful!)
while True:
    print("This never stops!")

While vs For

Use for when you know how many times to loop. Use while when you loop until a condition changes:

# For: known count
for i in range(10):
    print(i)

# While: unknown count
password = ""
while password != "secret":
    password = input("Enter password: ")
print("Access granted!")

break and continue

# break — exit immediately
while True:
    user_input = input("Enter 'quit' to exit: ")
    if user_input == "quit":
        break
    print(f"You entered: {user_input}")

# continue — skip to next iteration
num = 0
while num < 10:
    num += 1
    if num % 2 == 0:
        continue
    print(num)  # 1, 3, 5, 7, 9

while-else

The else block runs when the condition becomes False:

num = 1
while num <= 100:
    if num == 50:
        break
    num += 1
else:
    print("Loop completed normally")

# If break is hit, else doesn't run

Common Patterns

User Input Loop

name = ""
while not name:
    name = input("Enter your name: ")
print(f"Hello, {name}!")

Number Guessing Game

import random

secret = random.randint(1, 100)
guess = 0
attempts = 0

while guess != secret:
    guess = int(input("Guess a number (1-100): "))
    attempts += 1
    if guess < secret:
        print("Too low!")
    elif guess > secret:
        print("Too high!")

print(f"Correct! Took {attempts} attempts.")

Menu System

while True:
    print("\n1. Start")
    print("2. Settings")
    print("3. Quit")
    choice = input("Choose: ")
    
    if choice == "1":
        print("Starting game...")
    elif choice == "2":
        print("Opening settings...")
    elif choice == "3":
        print("Goodbye!")
        break
    else:
        print("Invalid choice")

Processing Until Empty

items = [1, 2, 3, 4, 5]
while items:
    item = items.pop()
    print(f"Processing: {item}")

Infinite Loops

# Game loop
while True:
    handle_input()
    update_game()
    render()
    if game_over:
        break

# Server loop
while True:
    request = get_request()
    process(request)

Avoiding Infinite Loops

# BAD: no exit condition
# while True:
#     print("forever")

# GOOD: always have a way out
count = 0
while count < 100:
    print(count)
    count += 1

# GOOD: use a flag
running = True
while running:
    user_input = input("Command: ")
    if user_input == "exit":
        running = False

Best Practices

  • Always have a way to exit the loop
  • Initialize variables before the loop
  • Update the condition variable inside the loop
  • Use for instead of while when the count is known
  • Add a timeout or max iteration count for safety
  • Use while True with break for infinite loops that need to exit

Mini Practice

  1. Write a countdown from 10 to 1
  2. Create a simple calculator that runs until the user types "quit"
  3. Write a number guessing game
  4. Create a menu system with while loop
  5. Process items from a list until it's empty

Up Next

Next: Functions →

Related Topics

Frequently Asked Questions about While Loops

What is While Loops in Python?

While Loops is a fundamental concept in Python. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn While Loops?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn While Loops.

Why is While Loops important in Python?

While Loops is essential for Python development. Understanding this concept will help you write better code and solve real-world problems more effectively.