A while loop in Python repeatedly executes a block of code as long as a given condition is true. The condition is checked before the execution of the loop’s body, and if the condition evaluates to True
, the body of the loop is executed. This process continues until the condition evaluates to False
.
Here’s a simple example to illustrate how a while loop works:
Example: Printing Numbers from 1 to 5
# Initialize the starting number
number = 1
# Define the while loop condition
while number <= 5:
print(number) # Print the current number
number += 1 # Increment the number by 1
Explanation:
- Initialization: The variable
number
is initialized to 1. - Condition: The loop condition
number <= 5
is checked. If the condition isTrue
, the loop’s body executes. - Body of the Loop: Inside the loop:
- The current value of
number
is printed. - The variable
number
is incremented by 1 usingnumber += 1
.
- The current value of
- Reevaluation: After the body of the loop is executed, the condition is checked again. This process repeats until
number
exceeds 5, at which point the condition evaluates toFalse
and the loop terminates.
Output:
1
2
3
4
5
The loop runs five times, printing the numbers from 1 to 5. When number
becomes 6, the condition number <= 5
is False
, so the loop stops