A while
loop repeatedly executes a block of code as long as a given condition remains True
.
while condition:
# code block to repeat
count = 1
while count <= 5:
print(count)
count += 1
The loop checks the condition before each iteration. If the condition is True
, the loop body runs. When the condition becomes False
, the loop ends.
# Example 1: Print even numbers up to 10
num = 2
while num <= 10:
print(num)
num += 2
# Example 2: Countdown from 5 to 1
count = 5
while count > 0:
print(count)
count -= 1
print("Blast off!")
# Example 3: Sum numbers until user inputs zero
total = 0
num = int(input("Enter a number (0 to stop): "))
while num != 0:
total += num
num = int(input("Enter a number (0 to stop): "))
print("Total sum:", total)
# Example 4: Infinite loop with break
while True:
response = input("Type 'exit' to quit: ")
if response == "exit":
break
print("Exited the loop.")
# Example 5: Loop through list using index
fruits = ["apple", "banana", "cherry"]
i = 0
while i < len(fruits):
print(fruits[i])
i += 1