Python While Loops
Learn how to use while loops in Python to repeat code execution based on conditions.
Python Loops
Python has two primitive loop commands:
whileloopsforloops
The while Loop
With the while loop we can execute a set of statements as long as a condition is true.
Example - Print i as long as i is less than 6:
i = 1
while i < 6:
print(i)
i += 1 Note: remember to increment i, or else the loop will continue forever.
The while loop requires relevant variables to be ready, in this example we need to define an indexing variable, i, which we set to 1.
The break Statement
With the break statement we can stop the loop even if the while condition is true:
Example - Exit the loop when i is 3:
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1 The continue Statement
With the continue statement we can stop the current iteration, and continue with the next:
Example - Continue to the next iteration if i is 3:
i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i) The else Statement
With the else statement we can run a block of code once when the condition no longer is true:
Example - Print a message once the condition is false:
i = 1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6") Practical Examples
Countdown Timer
countdown = 5
while countdown > 0:
print(f"Countdown: {countdown}")
countdown -= 1
print("Blast off!") User Input Validation
password = ""
while password != "secret":
password = input("Enter password: ")
if password != "secret":
print("Incorrect password, try again.")
print("Access granted!") Sum of Numbers
total = 0
number = 1
while number <= 10:
total += number
number += 1
print(f"Sum of numbers 1 to 10: {total}") Finding Factors
num = 12
factor = 1
factors = []
while factor <= num:
if num % factor == 0:
factors.append(factor)
factor += 1
print(f"Factors of {num}: {factors}") Infinite Loops
Be careful with while loops! If the condition never becomes false, the loop will run forever:
Example - This will run forever:
i = 1
while i < 6:
print(i)
# i is never incremented, so it will always be 1 To avoid infinite loops:
- Always ensure the loop variable is modified inside the loop
- Make sure the condition can eventually become false
- Use a counter or maximum iterations as a safety measure
Example - Safe loop with maximum iterations:
i = 1
max_iterations = 100
iterations = 0
while i < 6 and iterations < max_iterations:
print(i)
i += 1
iterations += 1
if iterations >= max_iterations:
print("Loop stopped due to maximum iterations") Nested While Loops
You can have while loops inside while loops:
Example - Multiplication table:
i = 1
while i <= 3:
j = 1
while j <= 3:
print(f"{i} x {j} = {i * j}")
j += 1
print("---")
i += 1 While Loop vs For Loop
When to use while loops vs for loops:
Use While Loop When:
- You don't know how many iterations you need
- The loop depends on a condition that may change unpredictably
- You need to loop until user input meets criteria
- You're waiting for an external condition
Use For Loop When:
- You know the number of iterations in advance
- You're iterating over a collection (list, string, etc.)
- You need a counter variable
- You're working with ranges of numbers