[Tutor] fibonacci.py task ???
John Patrick Gerdeman
j_gerdem at informatik.uni-kl.de
Tue Jun 24 15:40:26 CEST 2008
Fibonacci.py calculates the Fibonacci numbers (the sum of the two
previous numbers), also see
http://en.wikipedia.org/wiki/Fibonacci_number
Files that end in .py are python files. Much like .txt are text files
and .odc is OpenOffice Calc file.
Though you can name any file as you wish, the convention for the usual
files is to use the correct extension, so to avoid confusion.
(Sometimes it is preferable to use another extension, or to omit them
altogether, but that's not the point I'm trying to make here)
>
> Fibonacci.py
> # This program calculates the Fibonacci sequence
> a = 0
We'll initialize the variable a as 0. Since the first element of the
Fibonacci Sequence is 0
> b = 1
We'll initialize the variable b as 1. Since the second element of the
Fibonacci Sequence is 1
We have to supply 0 and 1 as starting values. Without these we wouldn't
know where to start our sequence. (You could potentially start the
sequence anywhere, e.g at a=5 and b=7, or over all prime numbers, it
would still be a Fibonacci sequence, though not the one commonly known)
> count = 0
We'll initialize the variable count
> max_count = 20
We'll initialize the variable max_count
> while count < max_count:
While count is smaller then max_count do the following
> count = count + 1
Increase count
> # we need to keep track of a since we change it
> old_a = a
> old_b = b
assign a and b to two help_variables, so we don't accidently change the
values
> a = old_b
a now holds the current sequence element
> b = old_a + old_b
b holds the next element
> # Notice that the , at the end of a print statement keeps it
> # from switching to a new line
> print old_a,
I guess this is supposed to show some of the programming basics, though
I find the contents of the while-loop rather more confusing then
necessary.
More information about the Tutor
mailing list