Python xrange with float

micuzzo picture micuzzo · Feb 3, 2015 · Viewed 7.5k times · Source

Beginner programmer here.

Is there a way to use float values within the bounds of xrange as well as the step value? I have seen a few solutions for stepping with a float but not for the actual bounds.

Essentially I would like to create a loop that steps down like this:

for x in xrange(5.5,0,0.1):
     print x

I was thinking of determining the difference between my two boundaries, dividing it by the step value to determine the number of steps needed and then inputting this as an integer value into the xrange function - but is there an easier way?

Thank you!

Answer

levi picture levi · Feb 3, 2015

You can define your own "xrange" for floats using yield. Because there is not built-in function to do that.

>>> def frange(start, stop, step):
...     x = start
...     while x < stop:
...         yield x
...         x += step

Then in you can do

>>>for x in frange(5.5,0,0.1):
...    print x