[Tutor] for loops ... (fwd)
Alan Gauld
alan.gauld at blueyonder.co.uk
Tue Nov 18 13:09:27 EST 2003
Tadey sent this to me separately, for completeness here is my
reply to him. (Spacing seems to have gone wild due to alphabet
changes, sorry)
Alan G.
> ... 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
I think I mention this somewhere in the tutor but maybe not strongly
enough. In python (and many other languages) equality is represented
by a double equals: ==
So
j == j + 1
would, as you expect, be nonsense and always false.
A single equals is what is known as "assignment". Some programmers
like to read it as "becomes", so
j = j + 1
is read as
j becomes j + 1
In fact some languages (Pascal, ADA, Smalltalk) use a different symbol
for assignment and use a single equals for equality - which is frankly
more sensible! So in Pascal it would look like:
j := j + 1
Notice the extra colon before the equals sign.
> 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 ??
Yes.
> So please, give me some background releted to that kind of
> equations/instructions (j = j + 1), how they "control" loops,
The while loop has the following abstract form:
<Initialise loop control value>
while <test value>:
< do some processing>
<change loop control value>
For example:
j = 1
while j < 10:
print j * 12
j = j+1
> 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 ...
That's pretty much right, let's walk through it:
>>> def tadey(glg):
result = 1
while glg > 0:
result = result * glg
glg = glg - 1
return result
We'll draw a table of the variables:
glg result
2 1 while glg > 0, first time
2 2 result = result * glg
1 2 glg = glg - 1
1 2 while glg > 0 , second time
1 2 result = result * glg
0 2 glg = glg - 1
0 2 while glg < 0, third time. Test if false so we
exit loop
0 2 return result
So the result is 2
Lets do it again for tadey(3):
glg result
3 1 while glg > 0, first time
3 3 result = result * glg
2 3 glg = glg - 1
2 3 while glg > 0 , second time
2 6 result = result * glg
1 6 glg = glg - 1
1 6 while glg < 0, third time.
1 6 result = result * glg
0 6 glg = glg - 1
0 6 while glg < 0, 4th time, test fails, loop exits.
0 6 return result
So the result is 6.
Finally, lets try:
>>> tadey(-1)
glg result
-1 1 while glg > 0, first time, test fails, loop is never
entered
-1 1 return result
Hopefully that makes sense?
Alan G.
More information about the Tutor
mailing list