While Loop in Python
A while loop in Python is used to execute a block of code repeatedly as long as a condition is true.
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 whileiis 5 or less. - Inside the loop,
print(i)displays the current value ofi. - Then
i += 1increasesiby 1. - When
ibecomes 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
countby 1. - When
countbecomes 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.