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

`for` Loop in Python [ English ]

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:

  • The number of iterations is known
  • You want to work with numbers or indexes

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

01234

Explanation

  • Starts from 0 by default
  • Stops before 5

5. Example with Start and Stop

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

Output

12345

6. Example with Step Value

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

Output

13579

Explanation

  • Increments by 2 each time

7. Reverse Looping

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

Output

54321

Explanation

  • Starts from 5
  • Decreases by 1
  • Stops before 0

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

  • range() does not include the stop value
  • Default start value is 0
  • Default step value is 1
  • Negative step is used for reverse looping

12. Summary

  • for loop with range() is used for numeric iteration

  • range() generates a sequence of numbers

  • Forms:

    • range(stop)
    • range(start, stop)
    • range(start, stop, step)
  • Supports:

    • forward looping
    • reverse looping
    • nested loops