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

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.