This is what I've got and I'm not sure why it's not working
def sum(n):
if (n>0):
print (n)
return sum(n)+sum(n-1)
else:
print("done doodly")
number = int(input(": "))
sum(number)
For example if the use inputs 5, I want to program to calculate the sum of 5+4+3+2+1. What am I doing wrong ?
Two things:
sum(n)
when computing sum
for n
won't do you much good because you'll recurse indefinitely. So the line return sum(n)+sum(n-1)
is incorrect; it needs to be n
plus the sum of the n - 1
other values. This also makes sense as that's what you want to compute.As such you can simplify your code to:
def sum(n):
if n == 0:
return 0
return n + sum(n - 1)
You forgot to return
when n==0
(in your else
)
>>> def Sum(n):
... if not n:
... return 0
... else:
... return n + Sum(n-1)
...
>>> Sum(5)
15
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With