Looping using iterators with fractional values
Steven Bethard
steven.bethard at gmail.com
Sat Jan 1 15:30:39 EST 2005
Mark McEahern wrote:
> drife wrote:
>
>> Hello,
>>
>> Making the transition from Perl to Python, and have a
>> question about constructing a loop that uses an iterator
>> of type float. How does one do this in Python?
>>
>>
> Use a generator:
>
> >>> def iterfloat(start, stop, inc):
> ... f = start
> ... while f <= stop:
> ... yield f
> ... f += inc
> ...
> >>> for x in iterfloat(0.25, 2.25, 0.25):
> ... print '%9.2f' % x
> ...
> 0.25
> 0.50
> 0.75
> 1.00
> 1.25
> 1.50
> 1.75
> 2.00
> 2.25
> >>>
>
Or use the numarray module:
py> import numarray as na
py> for f in na.arange(0.25, 2.25, 0.25):
... print '%9.2f' % f
...
0.25
0.50
0.75
1.00
1.25
1.50
1.75
2.00
Steve
More information about the Python-list
mailing list