Python Range Function.

Python Range Function.

·

2 min read

What is Python Range() Function?

The range() function in Python is used to generate a sequence of numbers within a specified range. It is commonly used in for loops to iterate over a sequence of numbers. The range() function can be called with one, two, or three arguments, depending on the desired behavior.

Syntax:

range(stop)

range(start, stop)

range(start, stop, step)

Parameters:

  • start (optional): Specifies the starting value of the sequence. If not provided, the default value is 0.

  • stop (required): Specifies the stopping value of the sequence. The range will generate numbers up to, but not including, this value.

  • step (optional): Specifies the increment or decrement between consecutive numbers in the sequence. The default value is 1.

Examples:

Example 1: Generating a sequence of numbers up to a given stop value.

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

In this example, the range() function is called with a single argument, which represents the stop value. The loop iterates over the generated sequence from 0 to 4, printing each number.

Example 2: Generating a sequence of numbers within a specific range.

for num in range(2, 8): 
    print(num)
Output: 2 3 4 5 6 7

In this example, the range() function is called with two arguments: start and stop. The loop iterates over the generated sequence from 2 to 7 (stop value is not included).

Example 3: Generating a sequence of numbers with a specified step.

for num in range(1, 10, 2): 
    print(num)
Output: 1 3 5 7 9

In this example, the range() function is called with three arguments: start, stop, and step. The loop iterates over the generated sequence from 1 to 9, incrementing by 2 in each iteration.

The range() function is a useful tool for creating numerical sequences in Python, especially in combination with loops. It provides flexibility in generating sequences with different starting points, stopping points, and step sizes.