While Loop in Python
A while loop in Python is used to repeat a block of code as long as a condition is true. It is useful when we don’t know in advance how many times we want to run the loop.
The condition is checked before every loop cycle. If it's true, the code inside the loop runs. If it's false, the loop stops.
Syntax:
while condition:
# block of code
Note: Just like in for loop, indentation is important in while loop to define which code belongs inside the loop.
Example 1: Print numbers from 1 to 5 using while loop
i = 1
while i <= 5:
print(i)
i += 1
Output:
1
2
3
4
5
Explanation:
- We start with
i = 1
. - The loop condition is
i <= 5
, which means the loop will run whilei
is 5 or less. - Inside the loop,
print(i)
displays the current value ofi
. - Then
i += 1
increasesi
by 1. - When
i
becomes 6, the condition is false and the loop stops.
Why We Use while
Loop?
- When we don’t know how many times: Use while loop if the number of repetitions is not fixed.
- Based on a condition: It repeats only as long as a condition is true.
- Useful in many real-life scenarios: Like waiting for user input, retrying until successful, etc.
Example 2: Real-life style – countdown timer
count = 5
while count > 0:
print("Countdown:", count)
count -= 1
Output:
Countdown: 5
Countdown: 4
Countdown: 3
Countdown: 2
Countdown: 1
Explanation:
- We start with
count = 5
. - The loop checks if
count > 0
. - Each time, it prints the countdown message and decreases
count
by 1. - When
count
becomes 0, the loop stops.
Summary:
- Used when: The number of repetitions is unknown and depends on a condition.
- Syntax:
while condition:
- Condition checked: Before every iteration.
- Loop stops: When the condition becomes false.