Search code examples
pythonwhile-loopanacondafibonacci

Fibonacci Sequence using Python


Hello I am trying to write a script that prompts the user for an integer number (n), then prints all the Fibonacci numbers that are less than or equal to the input, in that order. EXAMPLE:

Enter a number : 14

output is: 1 1 2 3 5 8 13

Here is what i have so far but not sure if it is the most efficient way? It is working correctly but I was wondering if there is a easier way to clean this up..

n = int(input("Enter a number: "))
a = 0
b = 1
sum = 0


while(sum <= n):
 print(sum, end = " ")
 count += 1
 a = b
 b = sum 
 sum = a + b

print(end = " ")

I am fairly new to python and am doing some practice but was not able to find a solution in textbook.


Solution

  • This way is efficient enough, but your code can do better

    n = int(input("Enter a number: "))
    a = b = 1
    
    while(b <= n):
     print(b, end = " ")
     a, b = b, a + b