A while loop in Python repeatedly executes a block of code as long as a given condition is true.
while condition:
# Code to be executed repeatedly
# ...
The condition
is evaluated before each iteration. If it's true, the code block is executed; otherwise, the loop terminates.
count = 0
while count < 5:
print(count)
count += 1
Output:
0
1
2
3
4
numbers = [1, 2, 3, 4, 5]
total = 0
i = 0
while i < len(numbers):
total += numbers[i]
i += 1
print(f"The sum is: {total}")
Output:
The sum is: 15
Explanation: This example iterates through a list using a counter, accumulating the sum of elements.
while True:
input_value = input("Enter a number (or 'quit' to exit): ")
if input_value.lower() == 'quit':
break
try:
number = int(input_value)
print("You entered:", number)
except ValueError:
print("Invalid input. Please enter a number or 'quit'.")
Explanation: This example demonstrates a loop that continues until the user enters 'quit'. It also includes error handling to prevent the program from crashing if the user enters non-numeric input.
#This is an infinite loop, avoid unless in specific scenarios
while True:
print("This will run forever!")
This will print "This will run forever" continuously until manually stopped.
Important Note:
It's crucial to ensure that the condition in a while loop eventually becomes false to prevent infinite loops, which can cause your program to hang.