python - while循环运行一次?

标签 python list function while-loop

编码新手,正在尝试解决此编码问题以进行学习。

提示:

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() 合并,因为 threefive 没有其他用途,因此您的最终代码将然后看起来像这样:

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/

相关文章:

python - 从 Python 列表列表到整数索引的逆映射

c# - 在 treeView 中取消选择

Python 3 : Input in cmd to return functions

删除嵌套列表中的重复项

C++ if/else 网格系统

JavaScript if 语句内部函数以避免除以零 NaN 结果?

python - 如何对 Tornado 进行单元测试?

python - 使用 CSV.QUOTE_NONNUMERIC 而不引用标题

python - 根据颜色图的 2D 颜色误差条

python - Python 中的快速、小型和重复矩阵乘法