Search code examples
pythonnested-loops

Nested Loops Fibonacci Sequence


I am trying to write a program which will ask the user to enter a number. I then need to validate it is in the fib sequence

Code:

# asking the user to input number
number = int(input("Enter a number: "))

# creating empty list to be filled
sequence = [0, 1]

x = -2
y = -1


# append items to list
for i in range(number):
    x+=2
    y+=2
# this code will be executed 'length' times
    sequence.append(x+y)

# This should be somewhere in the loop: 
if number in sequence:
    print("The number is in the Fibonacci sequence")
else:
    print("The number is not in the Fibonacci sequence")

Expected Output:

Fibonacci Sequence = 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ….

Enter a number: 5
>>> The number is in the Fibonacci sequence

Solution

  • You will need to do some iteration (or recursion) in order to find the sequence of Fibonacci numbers. Here is one way to do it with a while loop:

    number = int(input("Enter a number: "))
    
    sequence = [0, 1]
    
    i= 0
    while True:
        new_item = sequence[i] + sequence[i+1]
        if new_item == number or number in [0,1]:
            print("The number is in the Fibonacci sequence")
            break
        elif new_item > number:
            print("The number is not in the Fibonacci sequence")
            break
        sequence.append(new_item)
        i+=1
    

    Notice that you will iterate until the new item in your Fibonacci sequence is greater than or equal to the number the user input.