Python while Loops

Ka Kavitha V Updated 03 Oct 2026
6 min read

while Loops

Loops in Python

A loop executes a block of code repeatedly. Without loops, printing the numbers 1 to 100 would require 100 separate print() statements. With a loop, it takes two lines.

Python provides two primary looping constructs:

LoopRepeatsBest When
while loopAs long as a condition remains trueYou do not know in advance how many repetitions are needed
for loopOnce for each item in a sequence (list, range, string, and so on)You are processing a known collection of items

This lesson focuses on the while loop.

The while Loop

A while loop runs a block of code as long as a condition evaluates to True.

Syntax

while condition:
    # code to repeat

How It Works

  1. Python evaluates the condition.
  2. If it is True, the indented block runs once.
  3. Python goes back to step 1 and checks the condition again.
  4. When the condition becomes False, the loop ends and the program continues after the loop.

Each pass through the loop body is called an iteration.

Example: Counting Numbers

count = 0

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

print("Loop ended")

Expected output:

Count value: 0
Count value: 1
Count value: 2
Count value: 3
Count value: 4
Loop ended

Tracing the loop:

Iterationcount Beforecount < 5Action
10TruePrint 0, increase to 1
21TruePrint 1, increase to 2
32TruePrint 2, increase to 3
43TruePrint 3, increase to 4
54TruePrint 4, increase to 5
—5FalseLoop ends
  • The loop runs while count < 5.
  • count += 1 is essential. It moves count toward the point where the condition becomes False.

Note: Always update the variable used in the condition inside the loop. Otherwise, the condition never changes and the loop never ends.

Infinite Loops

If the condition never becomes False, the loop runs forever — an infinite loop:

count = 0

while count < 5:
    print("Count value:", count)
    # count += 1 is missing — this loop never ends!

If this happens, stop the program by pressing Ctrl + C in the terminal.

Initializing the Loop Variable

The variable used in the condition must exist and have a value before the loop starts.

attempts = 1

while attempts <= 3:
    print("Attempt number", attempts)
    attempts += 1

Expected output:

Attempt number 1
Attempt number 2
Attempt number 3

Without the line attempts = 1, Python would raise a NameError the first time it evaluated attempts <= 3, because the variable would not exist yet.

The break Statement

break ends the loop immediately, even if the condition is still True. The program continues with the first statement after the loop.

Example: Stop When a Match Is Found

number = 1

while number <= 10:
    if number == 6:
        print("Number found, exiting loop")
        break
    print(number)
    number += 1

Expected output:

1
2
3
4
5
Number found, exiting loop
  • The loop stops as soon as number becomes 6.
  • The remaining iterations (6 to 10) never happen.

The continue Statement

continue skips the rest of the current iteration and jumps back to check the condition for the next iteration.

Example: Skip a Specific Value

value = 0

while value < 7:
    value += 1
    if value == 4:
        continue
    print("Current value:", value)

Expected output:

Current value: 1
Current value: 2
Current value: 3
Current value: 5
Current value: 6
Current value: 7
  • When value is 4, continue skips the print().
  • The loop then continues normally with 5.

Important: In this example, value += 1 comes before continue. If the increment were placed after the continue, it would be skipped when value is 4, value would stay at 4 forever, and the loop would never end. With while loops, always make sure the loop variable is updated before any continue.

The else Block in a while Loop

A while loop can have an optional else block. It runs once, when the loop condition becomes False naturally — that is, when the loop finishes without hitting break.

Example: Loop Completion Message

steps = 1

while steps <= 3:
    print("Step", steps)
    steps += 1
else:
    print("All steps completed successfully")

Expected output:

Step 1
Step 2
Step 3
All steps completed successfully
  • The else block runs after the loop finishes normally.
  • It is useful for completion messages and for "not found" logic.

else Does Not Run After break

If the loop ends because of break, the else block is skipped.

x = 1

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

Expected output:

1
2

"Loop finished" is not printed, because the loop exited early with break.

Practical Use of while–else: Searching

The else block is a clean way to report that a search found nothing:

numbers = [4, 9, 15, 22]
target = 10
index = 0

while index < len(numbers):
    if numbers[index] == target:
        print("Found at index", index)
        break
    index += 1
else:
    print("Target not found")

Expected output:

Target not found

If the target is found, break runs and the else is skipped. If the loop checks every item without finding it, the else block reports the result.

The while True Pattern

When the stopping point is decided inside the loop, a common pattern is while True: combined with break:

attempts = 0

while True:
    attempts += 1
    print("Trying to connect... attempt", attempts)
    if attempts == 3:
        print("Connected!")
        break

Expected output:

Trying to connect... attempt 1
Trying to connect... attempt 2
Trying to connect... attempt 3
Connected!

while True: would loop forever on its own; the break provides the exit. This pattern is widely used for input validation and retry logic.

Practical Example: Validating User Input

while True:
    age_text = input("Enter your age: ")
    if age_text.isdigit():
        age = int(age_text)
        break
    print("Please enter a valid number.")

print("Your age is", age)

Example run:

Enter your age: twenty
Please enter a valid number.
Enter your age: 25
Your age is 25

The loop keeps asking until the input contains only digits. You cannot know in advance how many attempts the user will need, which is exactly the situation while loops are designed for.

Common Use Cases for while Loops

  • Repeating a prompt until user input is valid
  • Running background checks or polling for a status change
  • Implementing retry mechanisms (for example, reconnecting to a server)
  • Reading data until a condition is met
  • Game loops that run until the player quits

Common Mistakes

MistakeProblem
Forgetting to update the loop variableInfinite loop
Updating the variable after continueThe update can be skipped, causing an infinite loop
Not initializing the loop variableNameError
Off-by-one conditions (< vs <=)The loop runs one time too many or too few
Using while to step through a list by indexWorks, but a for loop is simpler and safer
  • Python for Loops — iterating over sequences
  • Python Range — generating number sequences for loops
  • Python if Statement — conditions used inside loops
  • Python pass Statement — placeholders in empty loop bodies

0 Comments

Reviewed before they appear

No comments yet.

Python
Ask about this post
AI Ask about this post

Ask questions about Python while Loops and get answers drawn from it.

Signed-in readers only.