In Python, a while loop repeatedly executes a block of code as long as a given condition is True. It is useful when you do not know in advance how many times you want to repeat a block, and the repetition depends on a condition (like user input or a counter reaching a limit).
True.False.break statement: Used to exit a loop early.do-while, but you can emulate it with while True and break.The basic syntax of a while loop is:
while condition:
# code block
# runs as long as condition is True
Before each iteration, Python evaluates condition. If it is True, the body of the loop runs; if it is False, the loop stops and control moves to the next statement after the loop.
This example uses a counter variable that starts at 0 and increments until it reaches 5.
count = 0
# Initialize the counter
while count < 5:
# Loop while count is less than 5
print("Count:", count)
# Increase count to avoid an infinite loop
count += 1
A while True loop runs forever unless you manually exit using break. This pattern is common when waiting for user input.
# Loop indefinitely until the user types 'exit'
while True:
user_input = input("Type 'exit' to stop: ")
# Check if the user wants to stop the loop
if user_input == "exit":
# Exit the loop using break
break
Many languages have a do-while loop that runs the body at least once before checking the condition. Python does not have this construct, but you can emulate it:
# Run the block at least once and then check the condition
while True:
print("This runs at least once")
if not condition: # replace 'condition' with your check
# Break when the condition is no longer satisfied
break
Here, the code inside the loop always executes once. The if not condition check decides when to exit using break, giving you do-while-like behaviour.
For the basic while loop example:
The program prints:
Count: 0
Count: 1
Count: 2
Count: 3
Count: 4
After printing Count: 4, the variable count becomes 5. The condition count < 5 is now False, so the loop stops.
In the infinite loop example, the program keeps asking for input until you type exit. At that point, the if condition becomes True, break is executed, and the loop ends.
while loop has a condition that will eventually become False to avoid infinite loops.count += 1) so that the condition can change.break to exit loops early when a certain condition is met (e.g., correct input received).do-while loop, use while True with a carefully designed break condition.while loop to print numbers from 10 down to 1.do-while loop using while True that asks the user to enter a number and stops only when they enter a positive number.0 and 20.