所以问题是:设计一个接受整数参数的函数,并返回从1到作为参数传递的数字的所有整数之和。例如,如果将50作为参数传递,则该函数将返回1,2,3,4 ...... .50的总和。使用递归计算总和。 我可以通过我的代码告诉我很多麻烦
def main():
numbers= int(input('Enter a number to add the sums: ')
mysum = sum_num(numbers,1)
def sum_num(numbers,mysum):
start=1
end=numbers
if start>end:
return 0
else:
return my_sum
main()
答案 0 :(得分:1)
def sumup(n):
# this one is your emergency break. you return 1 if n gets below
# a certain threshold, otherwise you'll end up with an infinite
# loop
if n <= 1:
return n
# here is the recursion step, we return (n + "the sum to n+1")
else:
return n + sumup(n-1)
print(sumup(50))
答案 1 :(得分:-1)
打高尔夫球:
def sumup(n):
return (n + sumup(n - 1) if n > 1 else n) if isinstance(n, int) else None