fibonacci sequencing difficulties in python

96 views Asked by At

(I'm in a basic computer science class, and this is homework)

I am trying to create a basic fibonacci sequence with "n" as the parameter.

what I have so far seems to be working fine when I run the program in idle

def fibonacci(n):
    a=0
    b=1
    n = input("How high do you want to go? If you want to go forever, put 4ever.")
    print(1)
    while stopNumber=="4ever" or int(stopNumber) > a+b:
       a, b = b, a+b
       print(b)
fibonacci(n)

but when I try to run the program so that it displays the info I get this error

  Traceback (most recent call last):
 File "C:/Users/Joseph/Desktop/hope.py", line 10, in <module> fibonacci(n)
 NameError: name 'n' is not defined

Any idea how I can fix this?

2

There are 2 answers

0
Dair On BEST ANSWER

Since your fibonacci function is taking an input there isn't exactly a need to pass a parameter. But in the case of your error n isn't defined in the global scope. I would just get rid of the n parameter. Also, just replace stopNumber with n.

def fibonacci():
    a=0
    b=1
    n = input("How high do you want to go? If you want to go forever, put 4ever.")
    print(1)
    while n == "4ever" or int(n) > a+b:
       a, b = b, a+b
       print(b)

fibonacci()
0
Elliott Frisch On

You shouldn't pass an n you haven't read from the user when you invoke fibonacci. Also, you're using stopNumber (not n). I think you wanted

def fibonacci():
    a=0
    b=1
    stopNumber = input("How high do you want to go? " +
        "If you want to go forever, put 4ever.")
    print(1)
    while stopNumber=="4ever" or int(stopNumber) > a+b:
       a, b = b, a+b
       print(b)

fibonacci()