Home → Lessons → Loops in Python

Loops in Python

Learn how to repeat a block of code using for and while loops.

Lesson 07 Beginner 20 min

What are Loops?

A loop is used to execute a block of code repeatedly.

Python mainly provides two types of loops:

for Loop

Used to iterate over a sequence or range of values.

while Loop

Repeats code while a condition remains True.

1. for Loop

The for loop is used to repeat a block of code for each item in a sequence.

Example
for i in range(5):
    print(i)
Output:
0
1
2
3
4

2. range() Function

The range() function generates a sequence of numbers.

Example
for i in range(1, 6):
    print(i)
Output:
1
2
3
4
5

The ending value in range() is not included.

3. while Loop

A while loop executes a block of code as long as its condition is True.

Example
i = 1

while i <= 5:
    print(i)
    i += 1
Output:
1
2
3
4
5

4. break Statement

The break statement stops the loop immediately.

for i in range(1, 6):

    if i == 4:
        break

    print(i)
Output:
1
2
3

5. continue Statement

The continue statement skips the current iteration and moves to the next iteration.

for i in range(1, 6):

    if i == 3:
        continue

    print(i)
Output:
1
2
4
5

6. Practical Example

We can use loops to print the multiplication table of a number.

Multiplication Table
number = 5

for i in range(1, 11):
    print(number, "x", i, "=", number * i)
Output:
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
...
5 x 10 = 50
Remember:

for is commonly used when iterating over a sequence or a known range.

while is useful when repetition depends on a condition.

Quick Quiz

Which keyword stops a loop immediately?

Finished this lesson?