The while loop in Python is used to execute a block of code repeatedly as long as a condition is True.
It is mainly used when:
while condition:
# code block
i = 1
while i <= 5:
print(i)
i += 1
Output
1
2
3
4
5
Explanation
i = 1ii by 1 each timei > 5i = 3
while i <= 7:
print(i)
i += 1
Output
3
4
5
6
7
i = 5
while i >= 1:
print(i)
i -= 1
Output
5
4
3
2
1
Explanation
i < 1num = 4
i = 1
while i <= 10:
print(num * i)
i += 1
total = 0
i = 1
while i <= 5:
total += i
i += 1
print("Sum =", total)
Output
Sum = 15
while Loopi = 1
while i <= 2:
j = 1
while j <= 3:
print(i, j)
j += 1
i += 1
i = 1
while i > 0:
print(i)
i += 1
⚠️ This loop never ends because the condition is always True.
while loop is used when repetition depends on a condition
It continues until the condition becomes False
Supports:
Requires careful control to avoid infinite loops