range() function in Python

Rumman Ansari   Software Engineer   2022-10-07   363 Share
☰ Table of Contents

Table of Content:


The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and stops before a specified number.

Syntax:

range(start, stop, step)

Parameter:

Parameters

Description

start

•Optional.

•An integer number specifying at which position to start.

•Default is 0

stop

•Required.

•An integer number specifying at which position to stop (not included).

step

•Optional.

•An integer number specifying the incrementation.

• Default is 1

Check type of range:

myvar = range(0, 3, 1)
type(myvar)

Output

range

Question 01:

Create a sequence of numbers from 0 to 5, and print each item in the sequence:

# myrange1 = range(0,5,1)
for i in range(0,5,1):
 print(i, end = ' ')

Output

0 1 2 3 4 

Question 02:

Create a sequence of numbers from 4 to 6, and print each item in the sequence:

for i in range(4,7,1):
 print(i, end = ' ')

Output

4 5 6 

Question 03:

Create a sequence of numbers from 4 to 20, but increment by 2 instead of 1:

for i in range(4,21,2):
 print(i, end = ' ')

Output

4 6 8 10 12 14 16 18 20