Understanding the While Loop in Python
| For Loop | While Loop |
|---|---|
| Used when we know the number of iterations in advance. | Used when we don’t know the exact number of iterations, loop runs until condition is False. |
| Iterates over a sequence (list, string, range, etc.). | Repeats a block of code based on a condition. |
Example:for i in range(5): print(i) |
Example:i=1 |
| Stops when the sequence ends. | Stops when the condition becomes False. |
The while loop repeats a block of code as long as the condition is True.
# Basic While Loop syntax
while condition:
# code to execute
statement
Flow: Check condition → if True → run code → check again → stop when condition is False.
Simple counting from 1 to 5:
count = 1
while count <= 5:
print(count)
count += 1
# Output: 1, 2, 3, 4, 5
Calculate sum of numbers from 1 to 5:
total = 0
num = 1
while num <= 5:
total += num
num += 1
print(total)
# Output: 15
Print even numbers from 1 to 10:
num = 1
while num <= 10:
if num % 2 == 0:
print(num)
num += 1
# Output: 2, 4, 6, 8, 10
Print odd numbers from 1 to 10:
num = 1
while num <= 10:
if num % 2 != 0:
print(num)
num += 1
# Output: 1, 3, 5, 7, 9
Print numbers from 6 to 10:
num = 1
while num <= 10:
if num > 5:
print(num)
num += 1
# Output: 6, 7, 8, 9, 10
Print numbers divisible by 3 between 1 and 15:
num = 1
while num <= 15:
if num % 3 == 0:
print(num)
num += 1
# Output: 3, 6, 9, 12, 15
Print countdown from 5 to 1:
num = 5
while num >= 1:
print(num)
num -= 1
# Output: 5, 4, 3, 2, 1
Print 5 stars using a while loop:
i = 1
while i <= 5:
print("*")
i += 1
# Output: * * * * *
Print table of 2:
i = 1
while i <= 10:
print("2 x", i, "=", 2*i)
i += 1
# Output: 2x1=2, 2x2=4, ..., 2x10=20
Print "Hello" 5 times:
i = 1
while i <= 5:
print("Hello")
i += 1
# Output: Hello (5 times)