-1

This is the code that I am running. No problem is coming up, but it doesn't give me an answer either. I can't find the problem.

def fibonacci(n):
    if n <= 0: 
        return False
    elif n == 1 or n == 2:
        return 1
    else:
        count = 1
        n1, n2 = 1, 1
        while count <= n:
            n1 = n2
            newn = n2+n1
            if n == count:
                return newn
            else:
                count += 1

fibonacci(3)
wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • 4
    It returns a value, but if you expect output, then you need to `print` it. – trincot Feb 20 '22 at 21:58
  • 3
    It doesn't look like n1 or n2 are ever changed. Is fibonacci returning 2 for every value of n? – somebody3697 Feb 20 '22 at 22:00
  • 1
    Welcome to Stack Overflow! Please take the [tour] and read [ask]. This is a Q&A site, so I edited your post to ask an actual question. If you'd like to make any further changes, you can [edit] it yourself of course. Speaking of that, you might want to clarify that "No *error* is coming up". – wjandrea Feb 20 '22 at 22:09

1 Answers1

0

You have to use print on a function call to see that function's return unless you are calling the function from inside the REPL.

Using your example code, make this change:

print(fibonacci(3))

There are two other issues that I see:

The first is you start count at 1 even though

elif n == 1 or n == 2:
    return 1

accounts for the first and second fibonacci number

The second is n1 and n2 are never updated

To address these, you can update your code like this

def fibonacci(n):
    if n <= 0: 
        return False
    elif n == 1 or n == 2:
        return 1
    else:
        count = 3 # if you're in this part of the code, you must be at the 3rd fibonacci number
        n1, n2 = 1, 1
        while count <= n:
            newn = n2+n1
            if n == count:
                return newn
            else:
                count += 1
                n1 = n2
                n2 = newn

for i in range(11):
    print(i, fibonacci(i))

Output:

0 False
1 1
2 1
3 2
4 3
5 5
6 8
7 13
8 21
9 34
10 55
wjandrea
  • 28,235
  • 9
  • 60
  • 81
somebody3697
  • 206
  • 2
  • 4