Skip to content

Python for loop range

  • by

In Python, the for loop is used to iterate over a sequence (such as a list, tuple, string, or range) and perform some operation on each item within the sequence. The range() function is often used in conjunction with the for loop to generate a sequence of numbers.

The basic syntax for a for loop with range() is as follows:

for variable in range(start, stop, step):
    # Code block to be executed for each iteration
  • start: The starting value of the sequence (inclusive). If omitted, it defaults to 0.
  • stop: The ending value of the sequence (exclusive). The loop will run until one less than this value. This parameter is required.
  • step: The step or increment between consecutive numbers in the sequence. If omitted, it defaults to 1.

Python for loop range example

Simple example code

1. Loop from 0 to 4 (exclusive)

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

2. Loop from 2 to 8 (exclusive) with a step of 2

for i in range(2, 9, 2):
    print(i)

3. Loop backward from 10 to 1 (exclusive) with a step of -1

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

4. Using the range() function to generate a list of numbers

numbers = list(range(1, 6))
print(numbers)

5. Sum of numbers from 1 to 5

# Initialize a variable to store the sum
sum_of_numbers = 0

# Loop through numbers 1 to 5 (inclusive) using range()
for num in range(1, 6):
    # Add the current number to the sum
    sum_of_numbers += num

# Print the result
print("Sum of numbers from 1 to 5:", sum_of_numbers)

Output:

Python for loop range

In this example, we’ll use a for loop and the range() function to calculate the sum of numbers from 1 to 5.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

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