0

(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?

3
  • If you created function like this, it shouldn't have any parameters, because you get them inside function from standard input. Deleting n would solve this error, however, there would be other errors and your algorithm is also wrong Commented Jun 12, 2015 at 5:51
  • @JosephMcMurray: The algorithm isn't wrong. Commented Jun 12, 2015 at 5:58
  • @MaciejBaranowski: His algorithm isn't incorrect. Commented Jun 12, 2015 at 6:00

2 Answers 2

1

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()
Sign up to request clarification or add additional context in comments.

Comments

0

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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.