can anyone advise me

Peter Otten __peter__ at web.de
Thu Apr 27 06:25:33 EDT 2006


micklee74 at hotmail.com wrote:

> why the output of this code :
> x = 0
> while x < 10:
>         z = 0
>         print x
>         x = x + 1
>         while z < x:
>                 print z,
>                 z = z + 1
> 
> is
> 
> 0
> 0 1
> 0 1 2
> 0 1 2 3
> 0 1 2 3 4
> 0 1 2 3 4 5
> 0 1 2 3 4 5 6
> 0 1 2 3 4 5 6 7
> 0 1 2 3 4 5 6 7 8
> 0 1 2 3 4 5 6 7 8 9
> 0 1 2 3 4 5 6 7 8 9 < ---extra
> 
> 
> instead of :
> 0
> 0 1
> 0 1 2
> 0 1 2 3
> 0 1 2 3 4
> 0 1 2 3 4 5
> 0 1 2 3 4 5 6
> 0 1 2 3 4 5 6 7
> 0 1 2 3 4 5 6 7 8
> 0 1 2 3 4 5 6 7 8 9
> 
> thanks

Hint: You can modify your code a bit to see where the offending extra line
comes from:

x = 0
while x < 10:
        z = 0
        print "x" + str(x)
        x = x + 1
        while z < x:
                print "z" + str(z),
                z = z + 1

Surprised? Replace the statement responsible for the extra number with a
bare print,  perhaps moving it around somewhat to avoid the extra blank
line -- and when it works rewrite the script with for loops and range() :-)

Peter



More information about the Python-list mailing list