Firstly, you’re not computing the Fibonacci numbers here. “n+=n” just
doubles n, wheras you want to add the preceeding 2 numbers, eg 0 + 1 ==>
1, then 1 + 1 ==> 2, then 1 + 2 ==> 3, then 2 + 3 ==> 5 and so on. So
you need to keep the current and previous numbers around (you would make
an initial state by settings these to 0 and 1 to start with).
The other thing is that your main programme above treats all the really
low numbers specially and then enters a loop. The condition’s basicly
I think you’d be better writing a generator which computes and yields
the Fibonacci numbers, and does nothing else. Have they been covered
in your course yet?
If not: a generator is a special kind of function which runs, often
indefinitely, but yields values partway through the computation as you
go, like you might when printing them.
Here’s a function which prints odd numbers:
n = 1
n += 2
That of course runs forever. Here’s a generator:
n = 1
n += 2
That actually does not run at all until you ask it for values. Like
for n in gen_odd():
Here we create the generator by calling “gen_odd()”. That just sets it
up. It doesn’t run. Then the for-loop iterates on it. Every time it does
that, the function runs until it hits a yield statement. Then you get
the value from the yield (“yield n”, above), to do with what you want
(here, we print it). Then the function runs some more when the for-loop
asks for the next value.
The nice thing is that a generator lets you write some progressive
computation (like the Fibonacci series) as just that computation - you
don’t need to hook it up to whatever you’re doing with those numbers.
From the outside, the generator looks like an iterable of those values:
a possibly infinite list, great for for-loops.
So I would write a generator for the series, and put it in a for-loop to
check that it works by printing the values.
Then just put a test in the for-loop: is n > m? If so, print it and
“break” out of the loop.
main programme to run it and iterate until your desired value
Cameron Simpson firstname.lastname@example.org