编码新手,正在尝试解决此编码问题以进行学习。
提示:
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000.
three = []
five = []
def threeList():
n = 1
while (n*3<1000):
result = n*3
three.append(result)
n += 1
return three
def fiveList():
n = 1
while (n*5<1000):
result = n*5
five.append(result)
n += 1
return five
threeList()
fiveList()
print(three,five)
这导致打印 [3] [5] 到控制台。
最佳答案
您的 return
是循环的一部分,这意味着在迭代结束时,您只是从函数中 return
而不是进行另一次迭代。将其移出循环,即:
def threeList():
n = 1
while (n*3<1000):
result = n*3
three.append(result)
n += 1
return three
此外,此 return
没有什么意义,因为您返回的是全局变量。没有必要返回已经可用的东西(我建议你阅读 variable scope ),所以完全摆脱这些 return
是安全的:
def threeList():
n = 1
while (n*3<1000):
result = n*3
three.append(result)
n += 1
事实上,由于您的两个函数差别很小,您应该重构您的代码并让一个函数接受乘数(因为这是唯一的区别)并返回填充列表。这次我们使用局部变量来创建结果列表,所以这次您需要返回
它,否则result
列表将在函数外不可用:
def my_func(multiplier):
result = []
n = 1
while (n*multiplier < 1000):
result.append(n*multiplier)
n += 1
return result
然后替换
threeList()
fiveList()
与
three = my_func(3)
five = my_func(5)
事实上,您可以将其与 print()
合并,因为 three
和 five
没有其他用途,因此您的最终代码将然后看起来像这样:
def my_func(multiplier):
result = []
n = 1
while (n*multiplier < 1000):
result.append(n*multiplier)
n += 1
return result
print(my_func(3), my_func(5))
关于python - while循环运行一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55555056/