A while loop is used to repeat a block of code as long as a condition is True.
It is commonly used when the number of repetitions is not known in advance.
The loop keeps running until the condition becomes False.
SYNTAX OF WHILE LOOP
while condition:
# code block
If the condition is True, the loop runs.
If the condition becomes False, the loop stops.
EXAMPLE 1: BASIC WHILE LOOP
count = 1while count <= 5:
print(count)
count += 1
This loop prints numbers from 1 to 5.
The count += 1 increases the value each time, preventing an infinite loop.
INFINITE LOOP
If the condition never becomes False, the loop runs forever.
while True:
print("This will run forever")
To stop an infinite loop manually, press Ctrl + C.
WHILE LOOP WITH IF CONDITION
num = 1while num <= 10:
if num % 2 == 0:
print(num)
num += 1
This prints even numbers from 1 to 10.
BREAK STATEMENT IN WHILE LOOP
The break statement stops the loop immediately.
num = 1while num <= 5:
if num == 4:
break
print(num)
num += 1
The loop stops when num becomes 4.
CONTINUE STATEMENT IN WHILE LOOP
The continue statement skips the current iteration and moves to the next one.
num = 0while num < 5:
num += 1
if num == 3:
continue
print(num)
This skips printing the number 3.
WHILE LOOP WITH ELSE
A while loop can also have an else block.
The else block runs when the loop finishes normally (not stopped by break).
num = 1while num <= 3:
print(num)
num += 1
else:
print("Loop finished successfully")
IMPORTANT POINTS
• Always make sure the condition eventually becomes False
• Update the loop variable inside the loop
• Use break and continue for better control
• Be careful to avoid infinite loops
WHY WHILE LOOPS ARE IMPORTANT
• Useful when repetitions depend on a condition
• Helpful for user input validation
• Used in real-world applications like login systems and menu-driven programs
Understanding the while loop helps you create dynamic and condition-based Python programs.