free geoip
28

Python For Loop with Range Exercises

In this tutorial, you will learn how to use the for loop with range() function in Python through clear explanations…

In this tutorial, you will learn how to use the for loop with range() function in Python through clear explanations and practical exercises. The range() function is one of the most common tools for generating sequences of numbers, making it essential for beginners learning to iterate in Python.

Python For Loop with Range Exercises"

1. What Is a For Loop in Python?

A for loop in Python allows you to repeat a block of code multiple times. It is often used when you know exactly how many times you want to run a statement. The basic syntax looks like this:

for variable in sequence:
    # code to execute

Here, the loop runs for each element in the given sequence (like a list, tuple, or range).

2. Understanding the range() Function

The range() function generates a sequence of numbers. It is often used with for loops to control how many times the loop should run. The syntax is:

range(start, stop, step)
  • start – The beginning of the range (inclusive, optional, default is 0)
  • stop – The end of the range (exclusive, required)
  • step – The difference between each number (optional, default is 1)

3. Example 1: Print Numbers from 0 to 9

This basic example prints numbers using range(10).

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

Output:

0
1
2
3
4
5
6
7
8
9

4. Example 2: Print Even Numbers

Use a step value in range() to print even numbers only.

for i in range(0, 21, 2):
    print(i)

Output:

0
2
4
6
8
10
12
14
16
18
20

5. Example 3: Calculate the Sum of Numbers

You can easily calculate the total sum of a sequence using a loop with range().

total = 0
for i in range(1, 11):
    total += i
print("Total sum:", total)

Output:

Total sum: 55

6. Example 4: Nested For Loop with Range()

A nested for loop means having one loop inside another. This is often used to generate tables or patterns.

for i in range(1, 4):
    for j in range(1, 4):
        print(f"i={i}, j={j}")

Output:

i=1, j=1
i=1, j=2
i=1, j=3
i=2, j=1
i=2, j=2
i=2, j=3
i=3, j=1
i=3, j=2
i=3, j=3

7. Example 5: Create a Multiplication Table

This exercise shows how to create a multiplication table using nested loops.

for i in range(1, 6):
    for j in range(1, 11):
        print(f"{i} x {j} = {i*j}")
    print()

Output (truncated):

1 x 1 = 1
1 x 2 = 2
...
5 x 10 = 50

8. Example 6: Countdown Using range()

You can use a negative step to make a countdown loop.

for i in range(10, 0, -1):
    print(i)
print("Blast off!")

Output:

10
9
8
7
6
5
4
3
2
1
Blast off!

9. Example 7: Loop Through List Indexes Using range(len())

If you need both the index and the element, use range(len(list)).

fruits = ["apple", "banana", "cherry"]
for i in range(len(fruits)):
    print(f"Index {i} = {fruits[i]}")

Output:

Index 0 = apple
Index 1 = banana
Index 2 = cherry

10. Exercise Section

Now it’s your turn! Try solving these exercises using for and range():

  1. Print all numbers between 1 and 100 that are divisible by 5.
  2. Find the factorial of a given number using for loop.
  3. Generate a triangle pattern using stars (*).
  4. Display all odd numbers from 1 to 50.
  5. Calculate the average of numbers between 1 and 20.

Example Solution – Factorial Calculation

num = 5
factorial = 1
for i in range(1, num + 1):
    factorial *= i
print("Factorial:", factorial)

Output:

Factorial: 120

11. Common Mistakes When Using range()

  • Forgetting that range() excludes the stop number.
  • Misunderstanding step values, especially negative steps.
  • Using range() with large values that create unnecessary loops.

12. Conclusion

The for loop with range() is a fundamental concept for every Python programmer. Mastering it allows you to write cleaner, faster, and more efficient loops for number generation, iteration, and data processing. Practice regularly with different parameters and challenges to build strong Python programming skills.

For more official Python documentation, visit the Python Control Flow Statements page.

rysasahrial

Leave a Reply

Your email address will not be published. Required fields are marked *