im trying to write a recursive function that returns the fibonacci number, but am getting a weird result. here's my code.

def fibonacci(a,b,n):
   a =a+b
   b = a+b
   n= n-2
   if n ==0:
      print b
      return b
   elif n ==1:
      print a
      return a
   else:
      fibonacci(a,b,n)

x = fibonacci(1,1,7)
print x

i get none as the x value but a legitimate integer as the a or b value, and i don't know why.

Recommended Answers

All 4 Replies

def fibonacci(a,b,n):
   a =a+b
   b = a+b
   n= n-2
   if n ==0:
      print b
      return b
   elif n ==1:
      print a
      return a
   else:
      fibonacci(a,b,n)

x = fibonacci(1,1,7)
print x

i get none as the x value but a legitimate integer as the a or b value, and i don't know why.

So a = a + b , and b = a + b , which means they are equal. Then you evaluate whether n == 0 or n == 1 and return either b or a respectively.

I think you need to re-check your logic.

Member Avatar for leegeorg07

thats because your printing the function, you should use:

print(fibonacci(1,1,7))
#it will return
13
None

i figured out what the problem was, though its not what either of you said.
"So a = a + b , and b = a + b , which means they are equal."
no that's not what is means.
a gets the value a +b, then b gets the value a +b, where a is new value.
for example
a = 1
b =1
a = a+b #a now equals 2.
b = a+b #b now equals 3.

"print(fibonacci(1,1,7))
#it will return
13
None"
my point is to not get none as the return.
here is the correct version of the code.

def fibonacci(a,b,n):
   if n ==0:
      return a
   elif n ==1:
      return b
   else:
      a =a+b
      b = a+b
      n= n-2
      val =fibonacci(a,b,n)
      return val

x = fibonacci(1,1,7)
print x
Member Avatar for leegeorg07

so in the end you didnt need our help

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.