[Tutor] for loops ... (fwd)

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Tue Nov 18 11:50:38 EST 2003



---------- Forwarded message ----------
Date: Tue, 18 Nov 2003 06:49:25 +0100
From: Tadey <tayiper at volja.net>
To: Danny Yoo <dyoo at hkn.eecs.berkeley.edu>
Subject: for loops ...

Hello ...


1.) yet on the beggining I had problem understanding, or better imaging
while loop,

>>> j = 1
>>> while j <= 12:
...         print "%d x 12 = %d" % (j, j*12)
...         j = j + 1

... the part, where it says j = j + 1 ... looked at first a bit illogical,
like 1 = 1 + 1, so 1 = 2 come after,so this equation seems illogical (the
value on both sides of = sign should be identical - that is the deffinition
of equation).

So I tryed to imagine it not as equation, but rather as some "instructon"
how number (set by variable should "change/increase" through "looping"
cicles.
So I tryed to type j = 1 then j = j + 1, and of course after print j it says
j = 2, so in case above (if j = 1) means variable j changes from 1 to 2, and
then from 2 to 3, every loop +1, and so on to 11 ... is that it  ??

So please, give me some background releted to that kind of
equations/instructions (j = j + 1), how they "control" loops, which has
higher "priority" - for better imaging  !!

Though that was relative simple case (for me)
.


2.)  Here it is something different, though it is again while loop with that
kind of "equation", but ...

I don't get it, how it print that high values as a result.

I thought, that it first "takes" dog value 2, defined in tadey(2), then
"calculates" current value for this loop, so dog = dog - 1, that gives 1,
than multiplicate with result, which is set 1, which gives the real result
... but as you see (if you calculate in my way), I didn't get the right
values.

>>> def tadey(glg):
            result = 1
            while glg > 0:
                   result = result * glg
                   glg = glg - 1
            return result

>>> tadey(6)
720
>>> tadey(5)
120
>>> tadey(4)
24
>>> tadey(3)
6
>>> tadey(2)
2
>>> tadey(1)
1
>>> tadey(0)
1
>>> tadey(-1)
1
>>> tadey(-2)
1
>>>

--->  So please, explain, how Python calculates/gets that results in this
case  ?!?



Thanks, Tadey





More information about the Tutor mailing list