Open In App

Python - range() for Float Numbers

Last Updated : 04 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The range() function in Python is often used to create a sequence of numbers. However by default, it works only with integers. What if we want to use range() with float numbers? Let’s explore how we ca work with range() with float numbers.

Using numpy.arange()

For a cleaner solution, we can use numpy, which provides a function called arange(). It works just like range(), but it supports floats.

Python
import numpy as np

for i in np.arange(0, 2, 0.5):
    print(i)

Output
0.0
0.5
1.0
1.5

Using a Custom Function(Most Efficient)

If we don’t want to use numpy, we can create our own function to mimic the behavior of range() for floats. Here’s how you can do that:

Python
def float_range(start, stop, step):
    while start < stop:
        yield start
        start += step

# Use the float_range generator to iterate over a range of floats
for i in float_range(0, 2, 0.5):
    print(i)

Output
0
0.5
1.0
1.5
  • We created a function float_range() that yields values from start to stop with a step size of 0.5. It behaves like a generator and allows us to loop through float numbers.

Using a While Loop

If we want to create a range with float numbers, we can use a while loop. This loop will allow us to control the start, stop, and step values, including floats.

Python
# Initialize the starting, stopping, and stepping values
start = 0
stop = 2
step = 0.5
#iterate until 'start' reaches or exceeds 'stop'
while start < stop:
    print(start)
    start += step

Output
0
0.5
1.0
1.5

Next Article
Article Tags :
Practice Tags :

Similar Reads