You should probably read some of the links sent to you earlier but here is
a stab at an explanation.
Richard Hultgren wrote on 12/08/2009 10:36:08 AM:
- Forwarded Message
From: Richard Hultgren hultgren1...@yahoo.com
To: tutor@python.org
Sent: Mon, December 7, 2009 2:53:40 PM
Subject: loops
I'm quite new but determined. Can you explain to me, step by step, what
is going on in the computer in this loop. I
hope I am not being too dumb!
a = 0
b = 1
count = 0
max_count = 20
The above steps are initialization of your variables. 'a' points to the
value 0, 'b' points to 1, etc.
Since the values of the variables are used within the loop we need to give
it somewhere to start, otherwise we will get an error.
while count max_count:
The while loop will continue until 'count max_count' evaluates to False
(20 loops, due to line below)
the loop is defined as everything that is indented below this line.
count = count + 1
Increase the value of count by one each loop iteration, otherwise the
statement 'count max_count' will never change value, and the loop will
never end.
# we need to keep track of a since we change it
old_a = a# especially here
old_b = b
Keep the old values of the variables since we want to add them together
for the new value of b and will change the values in the next steps.
a = old_b
b = old_a + old_b
reassign 'a' to the value of 'old_b'. If we didn't save the value of 'a'
into 'old_a' above we wouldn't know what it was anymore.
reassign 'b' to the sum of 'old_a' and 'old_b'
# Notice that the , at the end of a print statement keeps it
# from switching to a new line
print old_a,
prints the value of old_a followed by a space. Without the comma at the
end the print statement each loop would print on a new line.
The best way to follow what is happening is to trace the variables through
the program. you would get a table that loops something like :
max_count count a b old_a old_b
countmax_count OUTPUT
20 0 0 1 no ValueNo Value
T No output yet
20 1 1 1 0 1 T
0
20 2 1 2 1 1 T
0 1
20 3 2 3 1 2 T
0 1 1
20 4 3 5 2 3 T
0 1 1 2
20 5 5 8 3 5 T
0 1 1 2 3
20 6 8 13 5 8 T
0 1 1 2 3 5
.
.
.
20 19 2584676541812584T
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181
20 20 2584676541812584F
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181
(You might want to check the last two rows, not guaranteeing the values
are right)
In the last row countmax_count is False the loop won't run and therefore
nothing will change.
Hope this helps some, but would recommend you try following some of the
tutorials online for beginning programming to help explain some of the
concepts, feel free to ask here whenever you get confused.
Chris
___
Tutor maillist - Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor