"drife" <[EMAIL PROTECTED]> 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 <[EMAIL PROTECTED]>                  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to