3

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!

micuzzo
  • 165
  • 3
  • 12

2 Answers2

7

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
levi
  • 22,001
  • 7
  • 73
  • 74
  • I've seen this but I don't yet understand generators. Nevertheless, from my this will output an array, is that correct? – micuzzo Feb 03 '15 at 01:35
  • 1
    @micuzzo nope, `frange` in each loop will return the next float after adding the `step` to it. Beginning from `start` to `stop` floats. So, `yield` is like a `return` statement without stopping the function call. – levi Feb 03 '15 at 01:37
  • thanks for making the connection between defining the function and then calling it elsewhere, I am still at quite an elementary level. In saying this, does the definition of frange need to be in the same file as where it will be called from? @levi – micuzzo Feb 03 '15 at 01:44
  • @micuzzo That is your choice, you can define it in a module and import it from elsewhere or just define it in the same file. – levi Feb 03 '15 at 01:48
2

range expects integer arguments. But you can do this with:

for x in xrange(55,0,-1): print x*1.0/10

aa333
  • 2,556
  • 16
  • 23