Last modified: Feb 04, 2026 By Alexander Williams
Python While Loop Guide: Syntax & Examples
Control flow is a core concept in programming. It lets you decide which code runs and when. Python offers several tools for this. One of the most fundamental is the while loop.
This article will teach you everything about the while loop. You will learn its syntax, see practical examples, and understand how to use it effectively. We will also cover common pitfalls like infinite loops.
What is a While Loop in Python?
A while loop is a control flow statement. It allows code to be executed repeatedly. This happens as long as a specified condition remains true.
Think of it as a "while this is true, keep doing that" instruction. It is perfect for situations where you do not know in advance how many times you need to repeat an action.
For instance, reading lines from a file until the end. Or asking for user input until they provide a valid answer. The loop runs based on a condition, not a fixed count.
Basic Syntax of the While Loop
The structure of a while loop is simple and clean. It mirrors the logical thinking behind it. Understanding this Python Function Syntax Guide for Beginners can help with overall code structure.
# Basic while loop syntax
while condition:
# Code block to execute
statement_1
statement_2
# ...
The keyword while starts the loop. It is followed by a condition. This condition is an expression that evaluates to either True or False.
A colon (:) marks the end of the condition line. All the indented code beneath it is the loop's body. This body executes repeatedly. It runs as long as the condition is True.
The moment the condition becomes False, the loop stops. The program then moves on to the next line of code after the loop.
A Simple While Loop Example
Let's look at a basic example. This loop counts from 1 to 5.
# Initialize a counter variable
count = 1
# Loop while count is less than or equal to 5
while count <= 5:
print(f"Count is: {count}")
count = count + 1 # Increment the counter
print("Loop finished!")
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Loop finished!
Here is how it works. We start with count = 1. The condition count <= 5 is True. So, the loop body runs.
It prints the current count. Then it increases count by 1. This is crucial. Without this step, the condition would never become false.
The loop checks the condition again. Is 2 <= 5? Yes. The process repeats. This continues until count becomes 6. Then 6 <= 5 is False. The loop ends.
Controlling the Loop: Break and Continue
Python provides special statements to control loop flow. These are break and continue. They give you more precise control.
The break statement immediately terminates the entire loop. It stops the loop even if the condition is still True.
# Example of using break
number = 0
while number < 10:
number += 1 # Same as number = number + 1
if number == 5:
print("Found the number 5! Breaking out.")
break
print(f"Current number: {number}")
Current number: 1
Current number: 2
Current number: 3
Current number: 4
Found the number 5! Breaking out.
The continue statement is different. It skips the rest of the current iteration. The loop then jumps back to check the condition again.
# Example of using continue
number = 0
while number < 5:
number += 1
if number == 3:
print("Skipping number 3")
continue # Skip the print statement below
print(f"Processed number: {number}")
Processed number: 1
Processed number: 2
Skipping number 3
Processed number: 4
Processed number: 5
The Dreaded Infinite Loop
An infinite loop is a common mistake. It happens when the loop's condition never becomes False. The loop runs forever, consuming resources.
This usually occurs when you forget to update the variable in the condition.
# WARNING: This is an infinite loop!
# value = 5
# while value > 0:
# print(f"Stuck at {value}") # 'value' never changes, so condition is always True
To avoid this, always ensure something in the loop changes. This change should eventually make the condition False. Using break with a separate check is another safe strategy.
While Loop with Else Clause
Python's while loop can have an optional else clause. This is a unique feature. The else block executes only if the loop condition becomes False.
It does not run if the loop is terminated by a break statement.
# While loop with an else clause
counter = 0
while counter < 3:
print(f"Inside loop: {counter}")
counter += 1
else:
print("Loop condition became False. Else block executed.")
Inside loop: 0
Inside loop: 1
Inside loop: 2
Loop condition became False. Else block executed.
This is useful for search loops. You can use the else to handle the "not found" case cleanly.
Practical Example: User Input Validation
A classic use for a while loop is validating user input. You keep asking until you get a valid response.
# Practical example: Asking for a valid number
while True: # This creates an intentionally infinite loop
user_input = input("Please enter a positive number: ")
# Try to convert the input to a float
try:
number = float(user_input)
if number > 0:
print(f"Thank you! You entered {number}.")
break # Exit the loop with valid