得到错误答案的倍数和3&5

2024-04-18 22:41:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我看了别人的代码,并尝试了建议,但没有帮助。在python中,我需要将3和5的倍数加起来,但不包括100

我已经试过在StackOverflow中搜索了

def multiples():
  total2 = 0
  for x in range (1,100):
    if (x % 3 == 0) or (x % 5 == 0):
      total2 += x
      return total2

print(multiples())

它说3作为我的输出,这显然是错误的。我做错什么了


Tags: or代码inforreturnifdef错误
1条回答
网友
1楼 · 发布于 2024-04-18 22:41:45

return语句在if块的循环中,因此它将返回第一个匹配的数字,即3

只需将其移出循环:

def multiples():
  total2 = 0
  for x in range (1,100):
    if (x % 3 == 0) or (x % 5 == 0):
      total2 += x
  return total2

print(multiples())

相关问题 更多 >