In Python, a while loop is used to repeatedly execute a block of code as long as a given condition remains True. Unlike the for loop, which is typically used when you know the number of iterations in advance, the while loop is ideal for situations where the number of iterations is unknown (indefinite iteration).
Condition Evaluation: Before each iteration, Python checks the test condition.
Execution: If the condition is True, the code block inside the loop is executed.
Update: Usually, a variable inside the loop is updated to eventually make the condition False.
Termination: If the condition evaluates to False, the loop stops, and the program moves to the next line of code.
If the condition never becomes False, the loop will run forever, potentially crashing your program or freezing your computer. This usually happens if you forget to increment your counter variable.
The most common use of a while loop is to repeat an action until a counter reaches a certain limit.
count = 1 while count <= 5: print(f"Iteration number: {count}") count += 1 # Incrementing the counter is crucial
while loops are perfect for validating input or keeping a program running until the user decides to quit.
user_input = "" while user_input.lower() != "quit": user_input = input("Enter a message (type 'quit' to exit): ") if user_input.lower() != "quit": print(f"You said: {user_input}") print("Goodbye!")
Just like the for loop, a while loop can have an optional else block. It runs only when the condition becomes False. If the loop is terminated by a break statement, the else block is skipped.
timer = 3 while timer > 0: print(timer) timer -= 1 else: print("Blast off!")
You can create complex conditions using and, or, and not.
x = 0 y = 10 while x < 5 and y > 5: print(f"x: {x}, y: {y}") x += 1 y -= 1
| Feature | For Loop | While Loop |
| Usage | Iterating over a sequence (Lists, Ranges). | Repeating based on a condition. |
| Control | Automatic (handled by the sequence). | Manual (requires manual updates). |
| Best For | Known number of steps. | Unknown number of steps (Event-driven). |
Copyright ©2025. All Rights Reserved Emblab THE RAVE INNOVATION