【发布时间】:2022-12-25 08:22:27
【问题描述】:
我需要编写短代码来计算 1 到 N 之间的数字总和,然后得到 1 到 sum 之间的新数字总和。
程序输出示例: 输入数量:5
1 和 5 之间的总和 = 15
1 和 15 之间的总和 = 120
我的代码:
def summ_N(N):
total = 0
for N in range(1, N + 1):
total += N
print('Sum between 1 and N =', N, 'is: ', total)
return total
N = int(input('Input N: '))
summ_N(N)
summ_N(total)
我收到的错误消息:
Input N: 5
Sum between 1 and N = 5 is: 15
Traceback (most recent call last):
File "main.py", line 10, in <module>
summ_N(total)
NameError: name 'total' is not defined
【问题讨论】:
-
a = sum(range(N + 1)); b = sum(range(a + 1))
标签: python