Notes
Categories

`for` Loop in Python [ English ]

< Prev Next >

1. Introduction

The for loop in Python is used to repeat a block of code multiple times. When used with the range() function, it is especially useful for numeric iteration.

This approach is commonly used when:

2. Syntax

for variable in range(start, stop, step):
    # code block

3. Understanding range()

The range() function generates a sequence of numbers.

Forms of range():

  1. range(stop)
  2. range(start, stop)
  3. range(start, stop, step)

4. Basic Example

for i in range(5):
    print(i)

Output

0
1
2
3
4

Explanation

5. Example with Start and Stop

for i in range(1, 6):
    print(i)

Output

1
2
3
4
5

6. Example with Step Value

for i in range(1, 10, 2):
    print(i)

Output

1
3
5
7
9

Explanation

7. Reverse Looping

for i in range(5, 0, -1):
    print(i)

Output

5
4
3
2
1

Explanation

8. Loop for Table Example

num = 5

for i in range(1, 11):
    print(num * i)

9. Sum of Numbers

total = 0

for i in range(1, 6):
    total += i

print("Sum =", total)

Output

Sum = 15

10. Nested for Loop with range()

for i in range(1, 4):
    for j in range(1, 4):
        print(i, j)

11. Important Points

12. Summary

< Prev Next >