while Loop in Python
A while loop in Python is used to repeat a block of code as long as a condition remains true. Unlike a for loop, which runs for a fixed number of times, a while loop continues executing until its condition becomes false.
How the while Loop Works
- Python first checks the condition.
- If the condition is
True, the loop body runs. - After each iteration, the condition is checked again.
Example:
count = 1
while count <= 5:
print(count)
count += 1Real-Life Example
- Think about charging a phone.
- You keep charging it while the battery is not full.
- Once it reaches 100%, you stop.
Using break in a while Loop
The break statement stops the loop immediately.
Example:
while True:
number = int(input("Enter a number: "))
if number == 0:
breakUsing continue in a while Loop
The continue statement skips the current iteration.
Example:
num = 0
while num < 5:
num += 1
if num == 3:
continue
print(num)Common Mistake: Infinite Loop
A while loop becomes infinite if the condition never changes.
Example:
while True:
print("Running forever")Always make sure the loop condition can eventually become false.
Conclusion
The while loop is powerful but dangerous if misused. Use it when repetition depends on a condition, not a count. Use for loops when the number of iterations is known. Knowing when not to use while is as important as knowing how to use it.
