我有这段代码,但我很难理解为什么会返回这个值,希望有人能向我解释一下。我是循环和索引的新手,所以请多多包涵。
total = 0
while total < 10:
for i in range(3):
total += 1
total *= 2
print(total)
我无法理解这如何只返回 6
和 18
的值。
最佳答案
看看发生了什么:
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/