20 Examples of While Loops in Python
Master Python while loops with these clear, step-by-step examples.
What is a while loop in Python?
A while loop in Python repeatedly executes a block of code as long as a given condition is true.
1. Basic While Loop
Loop through numbers until a condition is met:
i = 0
while i < 5:
print(i)
i += 1
Output:
0
1
2
3
4
2. While Loop with a List
Iterate through a list until a condition is met:
fruits = ['apple', 'banana', 'mango']
i = 0
while i < len(fruits):
print(fruits[i])
i += 1
Output:
apple
banana
mango
3. While Loop with String
Iterate through the characters of a string:
text = "hello"
i = 0
while i < len(text):
print(text[i])
i += 1
Output:
h
e
l
l
o
4. While Loop with Break
Break the loop when a certain condition is met:
i = 0
while True:
if i == 5:
break
print(i)
i += 1
Output:
0
1
2
3
4
5. While Loop with Continue
Skip an iteration using the continue statement:
i = 0
while i < 5:
if i == 3:
i += 1
continue
print(i)
i += 1
Output:
0
1
2
4
6. While Loop with Else Clause
Execute a block after the loop ends:
i = 0
while i < 5:
print(i)
i += 1
else:
print("Loop ended")
Output:
0
1
2
3
4
Loop ended
7. While Loop with List Length
Loop through a list until a specific index:
fruits = ['apple', 'banana', 'mango']
i = 0
while i < len(fruits):
print(fruits[i])
i += 1
Output:
apple
banana
mango
8. While Loop with Nested Loops
Use nested while loops for complex iterations:
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
i = 0
while i < len(matrix):
j = 0
while j < len(matrix[i]):
print(matrix[i][j])
j += 1
i += 1
Output:
1
2
3
4
5
6
7
8
9
9. While Loop with Random Numbers
Generate random numbers until a condition is met:
import random
number = random.randint(1, 10)
while number != 5:
print(number)
number = random.randint(1, 10)
Output:
Random numbers until 5 appears
10. While Loop with User Input
Ask the user for input until a valid response is provided:
user_input = ''
while user_input != 'yes':
user_input = input('Do you want to continue? (yes/no): ')
print('You chose to continue!')
Output:
User input until ‘yes’ is entered
11. While Loop with Counter
Use a counter to track loop iterations:
counter = 0
while counter < 10:
print("Iteration:", counter)
counter += 1
Output:
Iteration: 0
Iteration: 1
...
Iteration: 9
12. While Loop with a Timer
Use a while loop to simulate a timer:
import time
seconds = 0
while seconds < 5:
print("Time passed:", seconds, "seconds")
time.sleep(1)
seconds += 1
Output:
Time passed: 0 seconds
Time passed: 1 seconds
...
13. While Loop with User Input Validation
Keep asking for input until a valid choice is made:
user_input = ''
while user_input not in ['yes', 'no']:
user_input = input('Do you want to continue? (yes/no): ')
print('You chose to', user_input)
Output:
User chooses 'yes' or 'no'
14. While Loop to Count Down
Use a while loop to count down:
count = 10
while count > 0:
print(count)
count -= 1
print("Blast off!")
Output:
10
9
8
...
Blast off!
15. While Loop to Find Factorial
Calculate the factorial of a number using a while loop:
number = 5
factorial = 1
while number > 0:
factorial *= number
number -= 1
print("Factorial is:", factorial)
Output:
Factorial is: 120
16. While Loop with Multiple Conditions
Use multiple conditions in the while loop:
i = 0
while i < 5 and i != 3:
print(i)
i += 1
Output:
0
1
2
17. Infinite While Loop with Break
Create an infinite loop and break on condition:
while True:
user_input = input("Type 'exit' to stop: ")
if user_input == 'exit':
break
else:
print("You typed:", user_input)
Output:
User types input until 'exit' is entered
18. While Loop with Dynamic List
Modify a list inside a while loop:
numbers = [1, 2, 3, 4]
while numbers:
print(numbers.pop(0))
Output:
1
2
3
4
19. While Loop to Check Prime Number
Check if a number is prime using a while loop:
num = 29
i = 2
is_prime = True
while i <= num // 2:
if num % i == 0:
is_prime = False
break
i += 1
if is_prime:
print(num, "is prime")
else:
print(num, "is not prime")
Output:
29 is prime
20. While Loop with Fibonacci Sequence
Generate Fibonacci sequence using a while loop:
a, b = 0, 1
while a < 100:
print(a, end=' ')
a, b = b, a + b
Output:
0 1 1 2 3 5 8 13 21 34 55 89