Python sum recursion

Asked

Viewed 126 times

0

Well, I’m doing this code that’s meant to add and print recursively.

The variable le is the amount of times I want, which would be an accountant to at the end inform the sum of the numbers written and z a parameter to finish recursion. Only at the end print None.

Could someone help me, explain why this happened.

def soma(le,q=0,z=1):
    h = float(input("Numero:"))
    if le > z:
        return soma(le, q+h, z+1)

def main():
    q = soma(4)
    print(q)

main()

1 answer

1

Its recursive function has only one criterion, which is when le > z, when this check is not true, your function should return the final result.

From what I understand of your code, h is the current value read, q is the accumulator and z is the recursive call counter.

Place return q + h at the end of its function:

def soma(le,q=0,z=1):
    h = float(input("Numero:"))
    if le > z:
        return soma(le,q+h,z+1)
    return q + h
  • I didn’t pay attention to that part!! I think I did!! I will continue practicing similar exercises. Thank you for your attention and help!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.