The range()
function in Python is used to generate a sequence of numbers, which is commonly used in loops like for
loops. It allows you to specify a start value, an end value, and a step value to control the sequence of numbers generated. The range()
function is often used in scenarios where you need to iterate over a sequence of numbers or indices.
The range()
function has the following syntax:
range(start, stop, step)
Generate a sequence of numbers from 0 to 4.
for i in range(5):
print(i)
range(5)
generates numbers from 0 to 4. The for
loop iterates over each number and prints it.Generate a sequence of numbers starting from a value other than 0.
for i in range(2, 6):
print(i)
range(2, 6)
generates numbers from 2 to 5. The loop prints these numbers.Generate a sequence of numbers with a specified step value.
for i in range(0, 10, 2):
print(i)
range(0, 10, 2)
generates numbers from 0 to 8, with a step of 2. The loop prints 0, 2, 4, 6, and 8.Generate a sequence of numbers in reverse order using a negative step.
for i in range(10, 0, -2):
print(i)
range(10, 0, -2)
generates numbers from 10 to 2, with a step of -2. The loop prints 10, 8, 6, and 4.You can use range()
to iterate over the indices of a list.
fruits = ['apple', 'banana', 'cherry']
for i in range(len(fruits)):
print(f"{i}: {fruits[i]}")
range(len(fruits))
generates indices for the list fruits
. The loop prints the index along with the corresponding element.stop
value is exclusive, meaning the sequence will not include the stop
value itself.start
and step
values are optional. If not provided, the default start
value is 0, and the default step
value is 1.range()
returns a range object, which is an immutable sequence. If you need a list of numbers, you can convert it using list(range(...))
.numbers = list(range(5))
print(numbers) # Output: [0, 1, 2, 3, 4]
The range()
function can also be used with a negative step to generate sequences in reverse order.
for i in range(10, 0, -1):
print(i)
start
value is greater than the stop
value and the step
is positive, or if the start
value is less than the stop
value and the step
is negative, an empty range is returned.Objective: Practice using the range()
function in Python.
Create a Python File:
Create a file named range_practice.py
.
Basic Loop:
Use range()
to print numbers from 0 to 9.
Example:
for i in range(10):
print(i)
Custom Range:
Use range()
to print numbers from 5 to 15 (inclusive) with a step of 3.
Example:
for i in range(5, 16, 3):
print(i)
Reverse Range:
Use range()
with a negative step to print numbers from 20 to 10.
Example:
for i in range(20, 9, -2):
print(i)
List Indices:
Use range()
to iterate through the indices of a list and print each element.
Example:
colors = ['red', 'green', 'blue']
for i in range(len(colors)):
print(f"{i}: {colors[i]}")
Convert to List: Convert the range to a list and print it.
Example:
print(list(range(5)))