python - 无法理解为什么返回此值

标签 python algorithm

我有这段代码,但我很难理解为什么会返回这个值,希望有人能向我解释一下。我是循环和索引的新手,所以请多多包涵。

total = 0
while total < 10:
    for i in range(3):
        total += 1
    total *= 2
    print(total)

我无法理解这如何只返回 618 的值。

最佳答案

看看发生了什么:

total = 0
while total < 10:
    for i in range(3):
        total += 1

total 现在等于 3。

total *= 2

total 现在等于 6。

print(total)

它打印“6”。 total 仍然是 < 10,所以它再次循环:

while total < 10:
    for i in range(3):
        total += 1

total 现在等于 6+3=9。

total *= 2

total 现在等于 18。

print(total)

它打印“18”。现在 total 大于 10,因此您的 while 循环停止。

关于python - 无法理解为什么返回此值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46588115/

相关文章:

Python list + list 与 list.append()

python - 转换 pandas 系列和日期时间对象

vala 库的 Python 绑定(bind)

python - Tensorflow 上的简单线性回归

algorithm - 在集合中寻找模式

c++ - 这看起来与旧问题相似但不同。给定一个大小为 n 的数组(允许重复的数字),找到缺失的 2 个数字

Python while循环,在类外打开和关闭它

algorithm - 二维离散游戏中的建筑物放置

c# - 快速排序算法 - 三的中位数

c++ - 为什么仅当输入为 5 时才会出现运行时错误?