Looping using iterators with fractional values

Mike Meyer mwm at mired.org
Sat Jan 1 15:35:09 EST 2005


"drife" <daranrife at yahoo.com> writes:

> 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?
>
> In Perl this construct quite easy:
>
> for (my $i=0.25; $i<=2.25; $i+=0.25) {
> printf "%9.2f\n", $i;
> }


Generally, you don't loop incrementing floating point values, as
you're liable to be be surprised. This case will work as you expect
because .25 can be represented exactly, but that's not always the
case.

Python loops are designed to iterate over things, not as syntactic
sugar for while. So you can either do the while loop directly:

i = 0.25
while i <= 2.25:
      print "%9.2f" % i
      i += 0.25

Or - and much safer when dealing with floating point numbers - iterate
over integers and generate your float values:

for j in range(1, 9):
    i = j * .25
    print "%9.2f" % i

    <mike
-- 
Mike Meyer <mwm at mired.org>			http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.



More information about the Python-list mailing list