Hello all,

I have started an new project which needs a Fibonacci sequence (all Fibonacci numbers below 4,000,000)

Here is my code for calculating Fibonacci numbers:

``````numbers_list = []
number1 = 1
number2 = 2
total = 0

while (total < 4000000):
total = number1 + number2
number1 = number2
number2 = total
numbers_list.append (total)

listlength = len(numbers_list)
print (numbers_list)
``````

I know it produces an ugly result (I will work on that soon), but it also outputs one number above 4,000,000 (5702887)
Why does it display this number?

Any help greatly appreciated

2
Contributors
1
20
Views
2 Years
Discussion Span
Last Post by Gribouillis

Because a new total is computed at line 7. This total is never tested at line 6. What you can do is

``````while True:
total = number1 + number2
number1, number2 = number2, total
if total >= 4000000:
break
else:
numbers_list.append (total)
``````

Make sure your editor is configured to indent python code with 4 spaces, which is the best way to do it.

Edited by Gribouillis

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.