-5
n= int(input())
for i in range(n+1):
    def f(x):
        print(x)

        if i<=1:
            f(i)

        elif i>1:
            f(i-1) + f(i-2)
4
  • 1
    I think you have some things confused here. You are defining a function n + 1 times inside the loop with def f(x): but never call it. This looks like you are trying to use a recursive and iterative approach together.
    – Mark
    Jun 2, 2019 at 22:35
  • You have no base case and you have defined a function inside a loop. Does this even run?
    – Mitch
    Jun 2, 2019 at 22:38
  • isn't the function called after the if and elif statement? Jun 2, 2019 at 22:39
  • 2
    @BhavikRoopchandani Not in the code you are showing. There is no f(n) being called anywhere. And even then your function is missing a return statement Jun 2, 2019 at 22:41

1 Answer 1

0

You need to define your fibonacci function before, like this :

def f(x):
    if(x <= 1):
        return x
    else:
        return (f(x - 2)+ f(x - 1))
n = int(input())
print(f(n))
2
  • 1
    Could shorten this to if x <= 1: return x. Also would avoid the infinite recursion of something like f(-1)
    – Mitch
    Jun 2, 2019 at 22:46
  • Should be <=, =< is not valid syntax
    – Mitch
    Jun 2, 2019 at 22:48

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.