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 blocki = 1 while i <= 5: print(i) i += 1Output
12345Explanation
i = 1ii by 1 each timei > 5i = 3 while i <= 7: print(i) i += 1Output
34567i = 5 while i >= 1: print(i) i -= 1Output
54321Explanation
i < 1num = 4i = 1 while i <= 10: print(num * i) i += 1total = 0i = 1 while i <= 5: total += i i += 1 print("Sum =", total)Output
Sum = 15while Loopi = 1 while i <= 2: j = 1 while j <= 3: print(i, j) j += 1 i += 1i = 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