[Tutor] (no subject)

ALAN GAULD alan.gauld at btinternet.com
Tue Mar 24 14:33:40 CET 2009



> I am sorry , some how how i missed it . code you pls explain this.
 
> for i in range(-10,11):
>   print '*'*(11-abs(i))
 OK, 
the range() function returns a list of numbers from -10 to +10.

the for loop assigns i to each value in turn

The print statement prints out the asterisk repeated (11-abs(i)) times
abs(i) returns the positive value of  i. This means abs(i) will take the 
values  10,9,8,7,....2,1,0,1,2,...8,9,10

So 11-abs(i) will take the values 1,2,3,4,...9,10,11,10,9,...3,2,1

This prints out the desired triangular pattern.

Does that make sense? You can explore this at the >>> prompt 
quite easily (I'll use a smaller range of values...):
>>> range(-3,4)
[-3, -2, -1, 0, 1, 2, 3]
>>> for n in range(-3,4):
...     print abs(n)
...
3
2
1
0
1
2
3
>>> for n in range(-3,4):
...     print 4-abs(n)
...
1
2
3
4
3
2
1
>>> for n in range(-3,4):
...     print '*' * (4-abs(n))
...
*
**
***
****
***
**
*

HTH,

Alan G.
http://www.alan-g.me.uk
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20090324/f205773e/attachment.htm>


More information about the Tutor mailing list