1
def fibonacci(n):
    if n==0:
        return 0
    if n==1 | n==2:
        return 1
    f = (fibonacci(n-1) + fibonacci(n-2))
    return f

Hi, I'm a python newbie and I want to implement a recursive fibonacci function, but my code (above) does not work. When I call this function the terminal prints the 6th line until the recursion depth limit is reached. What's the correct syntax to use here?

2 Answers 2

1

you need to make very small change => | to or

(Arithmetic OR to Logical OR)

def fibonacci(n):
    if n==0:
        return 0
    if n==1 or n==2:
        return 1
    f = (fibonacci(n-1) + fibonacci(n-2))
    return f


print fibonacci(6)
# 8

Another option is to use if (n==1)|(n==2): on line 4

hope it helps : )

Sign up to request clarification or add additional context in comments.

Comments

1

"|" is a arithmetic or, not a logic. Use "or"

   def fibonacci(n):
        if n==0:
            return 0
        if n==1 or n==2:
            return 1
        f = (fibonacci(n-1) + fibonacci(n-2))
        return f

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.