使用python 3,您如何更改此代码以打印1到20之间所有数字的总和?
n = 20
i=0
sum = 0
for i in range (1,n+1):
sum =+ i
i = i+1
print(sum)
答案 0 :(得分:4)
我能想到的最简单的方法是:
sum(range(1, 21)) # includes 20
您还可以使用循环:
s = 0
for i in range(21):
s += i
答案 1 :(得分:0)
n = 20
# this isn't needed, the for loop sets i: i = 0
sum = 0
for i in range (1, n+1):
sum += i
# Remove this line: i = i+1
# for i in range already increments i
print(sum)
您不应该使用变量名称sum
,因为已经有一个内置函数sum
,您甚至可以使用它。