Sometimes, you need a block of code to run repeatedly as long as a certain condition remains true. This is different from simply running code sequentially or making a single decision with if
. Python's while
loop provides exactly this capability. It's particularly useful when you don't know in advance how many times you'll need to repeat the actions.
Think of it like telling Python: "Keep doing this while this condition holds."
while
LoopThe basic syntax of a while
loop looks like this:
while condition:
# Code block to be executed repeatedly
# This block MUST be indented
statement1
statement2
# ... potentially update variables affecting the condition ...
Let's break this down:
while
keyword: This signals the start of the loop.condition
: This is a boolean expression (an expression that evaluates to either True
or False
), just like the conditions you used with if
statements. Examples: count < 5
, user_input != 'quit'
, is_valid == False
.:
: Marks the end of the while
statement header.while
line belong to the loop. This block is executed repeatedly. It's critically important that something within this block eventually causes the condition
to become False
, otherwise the loop will run forever!while
LoopThe flow of execution for a while
loop is straightforward:
condition
.condition
is True
, Python executes the entire indented code block.condition
is False
, Python skips the indented code block entirely and execution continues with the first statement after the loop.True
), Python goes back to Step 1 and re-evaluates the condition
.This check-execute-repeat cycle continues until the condition
evaluates to False
.
Flowchart illustrating the execution logic of a
while
loop.
Let's create a loop that prints numbers from 1 up to, but not including, 5.
# Initialize a counter variable BEFORE the loop
count = 1
# The loop continues as long as 'count' is less than 5
while count < 5:
print(f"Current count is: {count}")
# IMPORTANT: Update the counter inside the loop!
count = count + 1 # Or use the shorthand: count += 1
print("Loop finished!")
Output:
Current count is: 1
Current count is: 2
Current count is: 3
Current count is: 4
Loop finished!
Notice the three important parts for controlling this loop:
count = 1
sets up the starting state before the loop begins.count < 5
is checked before each potential iteration.count = count + 1
modifies the variable used in the condition inside the loop. Without this update, count
would always be 1, count < 5
would always be True
, and the loop would never end.If the condition in a while
loop never becomes False
, the loop will run forever. This is called an infinite loop. It's a common beginner mistake, usually caused by forgetting to include logic inside the loop that eventually changes the condition to False
.
Consider this example (don't run it unless you know how to stop it!):
# WARNING: This creates an infinite loop!
counter = 0
while counter >= 0:
print(f"Counter is {counter}. Still positive!")
# Oops! We forgot to change 'counter' in a way
# that makes the condition (counter >= 0) false.
# Maybe we meant to decrement it? Or check a different condition?
# Without a change, it will run forever.
counter = counter + 1 # This actually makes it *more* likely to stay >= 0!
If you accidentally run code with an infinite loop in a terminal or interactive interpreter, you can usually stop it by pressing Ctrl+C.
Always double-check that the logic inside your while
loop will eventually lead to the condition becoming False
.
while
loops shine when you need to repeat something until a specific event occurs, like getting valid input from the user.
# Initialize response to something that ensures the loop runs at least once
response = ""
# Keep asking until the user types 'quit'
while response.lower() != 'quit':
response = input("Enter some text (or type 'quit' to exit): ")
print(f"You entered: {response}")
print("Okay, quitting now. Goodbye!")
In this case, we don't know how many times the user will enter text before typing 'quit'. The while
loop handles this uncertainty perfectly, checking the response
after each input.
Mastering the while
loop allows you to write programs that can repeat tasks based on dynamic conditions, making your code much more flexible and powerful. You'll often use it for tasks like processing data until a condition is met, running simulations, or handling user interactions.
© 2025 ApX Machine Learning