Lessons
Courses
Notes in current language not found. Defaulting to English.

`while` Loop in Python [ English ]

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:

  • The number of iterations is not fixed
  • The loop depends on a condition

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

12345

Explanation

  • Starts from i = 1
  • Prints value of i
  • Increments i by 1 each time
  • Stops when i > 5

5. Example with Different Range

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

Output

34567

6. Reverse Looping

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

Output

54321

Explanation

  • Starts from 5
  • Decreases by 1
  • Stops when i < 1

7. Loop for Table Example

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

8. Sum of Numbers

total = 0i = 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

  • Loop runs while condition is True
  • Must update the variable inside loop
  • Otherwise, it may create an infinite loop
  • Suitable for condition-based repetition

12. Summary

  • while loop is used when repetition depends on a condition

  • It continues until the condition becomes False

  • Supports:

    • forward looping
    • reverse looping
    • nested loops
  • Requires careful control to avoid infinite loops