Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (50.2k points)

I am trying to execute the total sum of N whole numbers in Fibonacci

def fibo(n):

    if n<2:

        return 1

    else:

        res = fibo(n-1) + fibo(n-2)

        sum = sum + res

        return res, sum

n=7

sum = 0

for i in range(1, n):

    print(fibo(i))

print("Suma", sum)

#example: if n=7 then print : 1,1,2,3,5,8,13 and sum is 32

I am getting an error when I am having sum = sum + res.  

1 Answer

0 votes
by (108k points)
edited by

You are trying to calculate that in your function, but you just need to calculate sum in the for loop.

def fibo(n):

if n<2:

    return 1

else:

    res = fibo(n-1) + fibo(n-2)

    return res

n=7

sum = 0

for i in range(0, n):

    r = fibo(i) #I used r in order to call fibo once in each loop.

    sum += r

    print(r)

print("Suma", sum)

For more information regarding the same, do refer to the Python tutorial that will help you out in a better way. 

If you are a beginner and want to know more about Python, then do check out the below Python tutorial video that will help you in understanding the topic in a better way:

Browse Categories

...