Notes
Categories

`while` Loop in Python [ English ]

< Prev Next >

1. Introduction

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:

2. Syntax

while condition:
    # code block

3. How It Works

  1. The condition is checked
  2. If it is True, the loop executes
  3. After execution, the condition is checked again
  4. The loop continues until the condition becomes False

4. Basic Example

i = 1

while i <= 5:
    print(i)
    i += 1

Output

1
2
3
4
5

Explanation

5. Example with Different Range

i = 3

while i <= 7:
    print(i)
    i += 1

Output

3
4
5
6
7

6. Reverse Looping

i = 5

while i >= 1:
    print(i)
    i -= 1

Output

5
4
3
2
1

Explanation

7. Loop for Table Example

num = 4
i = 1

while i <= 10:
    print(num * i)
    i += 1

8. Sum of Numbers

total = 0
i = 1

while i <= 5:
    total += i
    i += 1

print("Sum =", total)

Output

Sum = 15

9. Nested while Loop

i = 1

while i <= 2:
    j = 1
    while j <= 3:
        print(i, j)
        j += 1
    i += 1

10. Infinite Loop

i = 1

while i > 0:
    print(i)
    i += 1

⚠️ This loop never ends because the condition is always True.

11. Important Points

12. Summary

< Prev Next >