Syntax
while condition:\n # code to repeatExamples
Basic While Loop
Repeating a block of code until a counter condition becomes False.
count = 0
while count < 5:
print(count)
count += 1
print("Done")While Loop with break
Using while True with break to create a loop that exits based on internal logic rather than a simple counter.
attempts = 0
while True:
attempts += 1
guess = attempts # simulate a guess
if guess == 3:
print(f"Found it after {attempts} attempts")
breakInput Validation Loop
A very common real-world use: repeat until the user provides valid input.
while True:
age_input = input("Enter your age: ")
if age_input.isdigit():
age = int(age_input)
break
print("Please enter a valid number")
print(f"Age accepted: {age}")While with else
The else block runs only if the loop completes without hitting a break.
numbers = [1, 3, 5, 7]
target = 4
i = 0
while i < len(numbers):
if numbers[i] == target:
print("Found!")
break
i += 1
else:
print("Target not found in the list")Best practices
- Always ensure the loop condition will eventually become False, or include a break - otherwise you create an infinite loop
- Use 'while True' with an explicit break when the exit condition is checked in the middle of the loop body, not just at the top
- Prefer a for loop over a while loop whenever you are iterating a known number of times or over a sequence
- The while...else construct is rarely used but is handy for 'search and report if not found' patterns
At a glance
- Purpose
- Scripting and general-purpose applications
- File extension
- .py
- Runs in
- Python interpreter
- Usually used with
- Python standard library and packages
Specifications & further reading
Related Python documentation
The if statement is Python's primary conditional control structure. It allows your program to make decisions by executing different code blocks based on whether a condition is True or False. The if statement is fundamental to creating dynamic, responsive programs that can adapt their behavior based on various conditions, user input, or data states.for
The for loop in Python is used to iterate over sequences like lists, tuples, strings, or any iterable object. Unlike traditional for loops in other languages that use counters, Python's for loop is more like a "for each" loop, automatically handling the iteration details. It's one of the most commonly used constructs in Python for processing collections and repeating actions.break and continue
break and continue give you fine-grained control over loop execution. break immediately exits the nearest enclosing loop entirely, skipping any remaining iterations. continue skips just the rest of the current iteration and jumps straight to the next one, without exiting the loop. Both work inside for and while loops.pass
pass is a null operation - a statement that does absolutely nothing when executed. It exists purely to satisfy Python's syntax, which requires every block (function, class, loop, conditional) to contain at least one statement. pass is commonly used as a temporary placeholder while you're still planning out code, or to intentionally leave a branch empty.