[Tutor] (no subject)
Daniele
d.conca at gmail.com
Tue Mar 24 15:06:25 CET 2009
> From: Padmanaban Ganesan <padhu.47 at gmail.com>
> Subject: Re: [Tutor] (no subject)
> Could any one explain me whats this in it .... abs(i)....???
>>> for i in range(-10,11):
>>> print '*'*(11-abs(i))
I'll try to explain it:
with the first line you are looping through all integer from i = -10 to 10
the idea is to use i as the number of * for each line.
using print '*' * i will print * exactly i times.
so one could write
for i in range(-10,11):
print '*'*i
but this will not work for negative values of i, so we use abs(i)
(i.e. the absolute value of i).
Now
for i in range(-10,11):
print '*'*abs(i)
will produce
**********
*********
********
*******
******
*****
****
***
**
*
*
**
***
****
*****
******
*******
********
*********
**********
which is not quite what we want, and that's the reason of the 11-abs(i) part.:
for i in range(-10,11):
print '*' * (11-abs(i))
so, for example, when i=-10 (the first line) we want only 1 *, and in
fact 11-abs(i) = 11-abs(-10) = 11-10 = 1, so we get print '*' * 1.
when i = -9 the expression gives 2, and so on. with i = 0 we get 11 *
and we start then going down as for i = 1 we have 10 *, for i=2 we
have 9 * and so on until i=10 which gives 1 *.
Hope my english was clear enough :(
More information about the Tutor
mailing list