[Tutor] test

Steven D'Aprano steve at pearwood.info
Mon Dec 27 14:58:41 CET 2010


Chrystal wrote:
> Hi guys
> 
> I'll be happy if someone can help evaluate the result of this statement:
> 
> for n in range (3, 20):
>> for x in range (2, n):
>> print (n)
>>
> 
> I tried but couldn't figure out why the loop returned such a result


It would help if you told us what result you get, what result you 
expected, and what you don't understand about it.

My guess is that you expected it to print:

2
2
3
2
3
4
2
3
4
5
...

but instead it prints:

2
3
3
4
4
4
5
5
5
5
...

Hint: you are print n each time, not x. n doesn't vary inside the inner 
loop, only in the outer loop.

To understand what is going on better, it might help if you run this 
instead:


for n in range(3, 20):
     for x in range(2, n):
         print('n = %d, x = %d' % (n, x))




-- 
Steven


More information about the Tutor mailing list