The while loop tests a condition before each iteration. If the condition is true, the loop's code block executes. If the condition is false, the loop stops.
Here's how a while loop works:
- Initialization: A variable is initialized with a starting value.
- Condition Check: The while loop checks the condition.
- Execution: If the condition is true, the code block inside the loop executes.
- Iteration: The loop returns to step 2, checking the condition again.
- Termination: The loop stops when the condition becomes false.
Examples:
- Printing numbers from 1 to 10:
i = 1
while i <= 10:
print(i)
i += 1
In this example, the condition i <= 10
is checked before each iteration. The loop continues as long as i
is less than or equal to 10. Once i
becomes 11, the condition becomes false, and the loop stops.
- Reading user input until a specific word is entered:
word = ""
while word != "quit":
word = input("Enter a word (or 'quit' to exit): ")
print(f"You entered: {word}")
This loop continues until the user enters the word "quit". The condition word != "quit"
is checked before each iteration. If the user enters "quit", the condition becomes false, and the loop stops.
In summary, the while loop tests a condition to determine whether to continue executing its code block. The condition is evaluated before each iteration, and the loop continues as long as the condition remains true.