Skip to main content

Command Palette

Search for a command to run...

Python Range Function.

Published
β€’2 min readβ€’View as Markdown
Python Range Function.

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.

Python

Part 7 of 9

Unlock Pythons power in our captivating series. From basics to advanced techniques, unleash your coding potential in a few episodes. Join us now and embark on a journey of learning and exploration.

Up next

Loops in Python.

What are the Loops in Python? In Python, a loop is a programming construct that allows you to repeat a block of code multiple times. It enables you to automate repetitive tasks and iterate over collections of data. Python provides two main types of l...

More from this blog

Aksh Darji

19 posts