while loop in Python
What is a while Loop? A while loop in Python is used to execute a block of code repeatedly as long as a specified condition remains True.
It is mainly used when we don’t know in advance how many times you want to execute the loop.
Syntax
while condition:
# code block Explanation:
- condition: A boolean expression (True or False).
- The loop runs while the condition is True.
- Once the condition becomes False, the loop stops.
Example: Basic while Loop.
Python
# Initialize variable
count = 1
# Run loop while condition is True
while count <= 5:
print("Count is:", count)
count = count + 1 # Increment to avoid infinite loop
Output: Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Explanation
- The loop starts with count = 1.
- It checks count <= 5 → True.
- Prints the value and increases it by 1.
- When count becomes 6, the condition becomes False, and the loop stops.
Infinite Loop Example If we forget to update the variable inside the loop, the loop never ends.
Python
# Warning: This will run forever!
x = 1
while x <= 5:
print("x =", x)
# missing x = x + 1 So, always ensure the condition will eventually become False.