Python Control Statements
Python While Loop
Learn Python While Loop with clear explanations, Python examples, and practical programming guidance.
What is a Python while loop?
A while loop repeats an indented block as long as its condition is true. It is useful when the number of iterations is not known in advance, such as reading input until it is valid or processing work until a queue is empty.
Syntax and execution flow
while condition:
# code runs while condition is True
update_state()- Python evaluates the condition.
- If it is true, Python runs the indented body.
- The loop state changes.
- Python evaluates the condition again.
- The loop ends when the condition becomes false.
Simple while loop
Always make sure the loop state can change. Otherwise, the condition may remain true forever:
counter = 0
while counter < 5:
print(counter, "Hello")
counter += 11 Hello
2 Hello
3 Hello
4 Hello
Repeating until user input is valid
A while loop is useful when the program should keep asking until the user enters an acceptable value:
password = ""
while len(password) < 8:
password = input("Enter at least 8 characters: ")
print("Password length is valid")In production code, also handle input limits, cancellation, and validation rules appropriate to the application.
Calculating a sum with a while loop
number = 1
total = 0
while number <= 15:
total += number * number
number += 1
print(total)Finding numbers divisible by 5 or 7
number = 1
while number <= 50:
if number % 5 == 0 or number % 7 == 0:
print(number, end=" ")
number += 1Checking prime numbers
A number is prime when it is greater than one and has no divisors other than one and itself. The loop below checks possible divisors up to the square root of the number:
def is_prime(number):
if number < 2:
return False
divisor = 2
while divisor * divisor <= number:
if number % divisor == 0:
return False
divisor += 1
return True
numbers = [34, 23, 75, 11]
for number in numbers:
print(number, is_prime(number))23 True
75 False
11 True
Checking an Armstrong number
An Armstrong number is equal to the sum of its digits raised to the power of the number of digits. The digit count matters; raising every digit only to the power of one is not a general Armstrong-number test:
number = 153
original = number
digits = len(str(number))
total = 0
while number > 0:
digit = number % 10
total += digit ** digits
number //= 10
if total == original:
print("Armstrong number")
else:
print("Not an Armstrong number")Creating a multiplication table
number = 21
counter = 1
while counter <= 10:
print(number, "x", counter, "=", number * counter)
counter += 121 x 2 = 42
21 x 3 = 63
21 x 4 = 84
21 x 5 = 105
21 x 6 = 126
21 x 7 = 147
21 x 8 = 168
21 x 9 = 189
21 x 10 = 210
Using break
break immediately exits the nearest while loop:
counter = 0
while counter < 8:
if counter == 4:
print("Stopping at", counter)
break
print("Counter:", counter)
counter += 1Counter: 1
Counter: 2
Counter: 3
Stopping at 4
Using continue
continue skips the remaining statements in the current iteration. Update the counter before continuing so the loop cannot get stuck:
counter = 0
while counter < 8:
counter += 1
if counter == 4:
continue
print(counter)2
3
5
6
7
8
Using pass
pass is a placeholder. It does not skip the iteration or stop the loop:
counter = 0
while counter < 5:
if counter == 2:
pass
print(counter)
counter += 11
2
3
4
Using else with a while loop
The else block runs when the loop condition becomes false naturally. It is skipped when break exits the loop:
counter = 0
while counter < 3:
print(counter)
counter += 1
else:
print("Loop completed successfully")1
2
Loop completed successfully
Infinite loops
An infinite loop occurs when its condition never becomes false. This may be intentional for a service loop, but it should always have a safe exit or shutdown mechanism:
counter = 0
while True:
print(counter)
counter += 1
if counter == 3:
breakDo not use while True accidentally. Check that every normal path updates the state or reaches a break.
Common mistakes
- Forgetting to update the counter or condition value.
- Using
continuebefore the update, which can create an infinite loop. - Using
breakwhen you only need to skip one iteration. - Writing a condition that can never become false.
- Using a
forloop when iterating over a known collection would be clearer.
Best practices
- Initialize the loop state before the loop starts.
- Keep the condition simple and easy to verify.
- Update the loop state in one obvious place.
- Use helper functions for complex validation or processing.
- Test boundary cases such as zero, empty input, negative numbers, and the first value that should stop the loop.
Further Reading
Continue learning with these related Python tutorials:
Continue learning
