Python while Loops – Repeating Tasks with Ease

Last updated 5 months, 1 week ago | 459 views 75     5

Tags:- Python

Loops are a fundamental part of programming, allowing you to repeat a block of code as long as a condition is true. In Python, the while loop is one of two main loop types (the other is for).

This tutorial covers:

  • How while loops work

  • Syntax and flow

  • Examples with explanations

  • Controlling loops with break and continue

  • Common pitfalls and best practices

  • A complete example at the end


✅ What Is a while Loop?

A while loop repeats code as long as a condition remains true. It's useful when you don't know in advance how many times you'll need to loop.

Syntax

while condition:
    # code block

As long as condition is True, Python executes the code block.


Example 1: Basic Loop

count = 1

while count <= 5:
    print("Count:", count)
    count += 1

Output:

Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

 count += 1 increases count each time, eventually making the condition False to stop the loop.


Example 2: Infinite Loop (Be Careful!)

while True:
    print("This will run forever!")

This loop will never stop unless:

  • You use break (see below)

  • You interrupt it manually (Ctrl+C)


⛔ Breaking Out of a Loop – break

Use break to exit a loop early, even if the condition is still True.

while True:
    user_input = input("Enter 'q' to quit: ")
    if user_input == 'q':
        break
    print("You entered:", user_input)

Skipping Iterations – continue

Use continue to skip the current iteration and go to the next one.

x = 0

while x < 5:
    x += 1
    if x == 3:
        continue  # Skip printing 3
    print(x)

Output:

1
2
4
5

else Clause with while

The else block runs after the loop ends normally (not via break).

x = 0

while x < 3:
    print(x)
    x += 1
else:
    print("Loop finished without break.")

Common Patterns

Waiting for Correct Input

password = ""

while password != "admin123":
    password = input("Enter password: ")

print("Access granted")

Counting or Accumulating

total = 0
number = 1

while number <= 5:
    total += number
    number += 1

print("Sum:", total)

Common Pitfalls

Mistake Why It Happens Solution
Infinite loop Condition never becomes False Update loop variables inside loop
Forgetting : after while SyntaxError Always add :
Improper indentation IndentationError Indent all loop content properly
Using = instead of == Assignment instead of comparison Use == in condition

Tips and Best Practices

  • Use counters or variables to control the loop.

  • Avoid infinite loops unless intentional.

  • Use break sparingly to avoid unreadable logic.

  • For known-length iteration, prefer a for loop.

  • Keep conditions clear and simple.


Complete Example: Number Guessing Game

import random

secret_number = random.randint(1, 10)
guess = None

while guess != secret_number:
    guess = int(input("Guess a number (1-10): "))
    if guess < secret_number:
        print("Too low!")
    elif guess > secret_number:
        print("Too high!")

print("You guessed it!")

Summary Table

Feature Description
Loop type while loop
Terminates when Condition becomes False
Keywords used while, break, continue, else
Use case Unknown number of iterations
Risks Infinite loop if condition never changes

What's Next?

After learning while loops, explore:

  • for loops for fixed iterations

  • range() function

  • Nested loops

  • Using loops with lists, dictionaries, and files