Hi, I'm trying to loop through vaules less than 1 eg say from 0.1-0.9. I tried the code below and I get the error "ValueError: xrange() arg 3 must not be zero". My question is, is it possible to loop through decimal values.

for x in xrange(0.1,0.9,0.1):
     print x

Thanks in advance for your reply.

The Python functions xrange() and range() only take integer values. For floating point values you have to roll your own function. I called mine frange() ...

def frange(start=0, stop=0, step=1.0):
    """similar to xrange, but handles floating point numbers"""
    if step <= 0:
        while start > stop:
            yield start
            start += step
    else:
        while start < stop:
            yield start
            start += step

# testing ...
for x in frange(1.5, 4.7):
    print(x)

print("-"*20)

#testing count down ...
for x in frange(11.2, -4, -2.9):
    print(x)

"""
my result -->
1.5
2.5
3.5
4.5
--------------------
11.2
8.3
5.4
2.5
-0.4
-3.3
"""

The module numpy has an arange() function ...

# module numpy (numeric python extensions, high speed)
# free from: http://sourceforge.net/projects/numpy

import numpy as np

for x in np.arange(11.2, -4, -2.9):
    print x

"""
my result -->
11.2
8.3
5.4
2.5
-0.4
-3.3
"""
commented: Nice use of generators +6
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.