我想创建一个程序,它接受用户整数输入,创建一个列表,然后使用递归 添加列表。问题是当我输入6时出现了15,而 的答案应该是(0 + 1 + 2 + 3 + 4 + 5 + 6)= 21。为什么数学是错误的?我想,那一定是在某处索引,因为如果你省略了6你得到15Python - 创建一个整数列表并使用递归来添加它们
#Program which accepts a number from the user
#take the numbers 0 to the number input
#and gives a total of the numbers
def main():
#Get the number from the user to define upper end of range
num = int(input('Enter a non-negative integer: '))
#Create the list of numbers
numbers = list(range(0,num, 1))
#Get the sum of the list of numbers
my_sum = range_sum(numbers, 0, - 1)
#Display the total
print('The sum of 0 to', num, 'is: ', my_sum)
def range_sum(num_list, start, end):
if start < end:
return 0
else:
return sum(num_list)
#call the main function
main()
您应该修复缩进。 'list(range())'应该缩短为只使用'range()'。 – jorgenkg
另外,'range(0,num,1)'只是'range(num)' – jonrsharpe
查看'numbers'中的数字。是否真的如你所期望的那样,然后查看“范围”的文档以查明原因。 – Daniel