0

u am starting to learn python, and want to get some experience with functions , for instance i have wrote following simple code in python

def fibonacci(n):
    if n == 1:
        return 1
    elif n == 2:
        return 1
    elif n > 2:
        return fibonacci(n-1)+fibonacci(n-2)

    for n in range(1, 4):
        print(n,", ",fibonacci(n))

but when i have run this code, i am getting just this line

C:\Users\Dato\Desktop\Python_codes\venv\Scripts\python.exe C:/Users/Dato/Desktop/Python_codes/fibonacci.py

Process finished with exit code 0

so why does not it shows me result?

7
  • 3
    Indenting is important in Python. Your for loop is inside the function. Commented Jan 14, 2019 at 21:21
  • 1
    your for loop is inside your function definition. If you unindent the last 2 lines it should work. Commented Jan 14, 2019 at 21:22
  • how to indicate that function is finished? Commented Jan 14, 2019 at 21:23
  • @datodatuashvili return finishes the function here. Commented Jan 14, 2019 at 21:23
  • then why is loop inside function? Commented Jan 14, 2019 at 21:24

3 Answers 3

1

The issue you're having is that you never call the function fibonacci.

I think you've got your tabbing off,

    for n in range(1, 4):
        print(n,", ",fibonacci(n))

shouldn't be inside the function.

Try this:

def fibonacci(n):
    if n == 1:
        return 1
    elif n == 2:
        return 1
    elif n > 2:
        return fibonacci(n-1)+fibonacci(n-2)

for n in range(1, 4):
    print(n,", ",fibonacci(n))
Sign up to request clarification or add additional context in comments.

2 Comments

wait what is different i can't guess
The way the function is written in the question, for n in range(1, 4): print(n,", ",fibonacci(n)) is inside the function and therefore the function never gets called
1

you miss the callign part. You just defined a function.

Now, you need to call it.

add

fibonacci(42)

at the end of your code

Comments

0

Im not sure on how you call the function, could you provide more information about that?

import random

any_number = randint()
print(fibonachi(any_number))

2 Comments

so i would like to understand what is meaning of indention here
sorry not sure i understand the question.

Your Answer

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