def difference1():
answer = 0
for a in range(1, 100):
sum1 = a**2
sum1 += answer
print(answer)
difference1()
为什么我的代码打印为0?我希望将1到100之间的所有数字加在一起。我可能只是犯了一个愚蠢的错误,但我无法弄清楚。
答案 0 :(得分:2)
当您将answer
添加到sum1
时,您正在向sum1
添加answer
!
此外,您的range
中有错:它上升到但不包括停止值:
def sum_of_squares(upto):
answer = 0
for i in range(1, upto + 1):
answer += i*i
return answer
print(sum_of_squares(100)) # => 338350
对于奖励积分,它也可以写成
def sum_of_squares(upto):
# turn the loop into a generator expression
return sum(i*i for i in range(1, upto + 1))
或
def sum_of_squares(upto):
# sum of squares formula
return upto * (upto + 1) * (2*upto + 1) // 6
答案 1 :(得分:1)
你永远不会改变答案'可变,这就是为什么它总是0,因为你指定它。
这样做:
def difference1():
answer = 0
for a in range(1, 100):
sum1 = a**2
answer += sum1 #the change is on this line
print(answer)
difference1()
答案 2 :(得分:0)
您想要添加错误的变量:
answer += sum1
答案 3 :(得分:0)
在此行sum1 += answer
上,您已将答案声明为0
,并将其添加到sum1
。它目前看起来像这样:sum1 = sum1 + 0
。您希望它看起来像这样:answer = answer + sum1
。因此,请改用此表达式:answer += sum1
。
答案 4 :(得分:0)
您的范围不正确,您将答案添加到 sum1
并且没有将 answer
添加到 sum
您可以直接将a**2
添加到answer
def difference1():
answer = 0
for a in range(101)
answer += a**2
return answer
print(difference1())