为什么这是以下代码的输出?

时间:2019-03-29 01:34:57

标签: python

我无法理解为什么此代码的输出为16。如果无法正确格式化任何内容,我感到抱歉。

我已经编写了几次代码,以确保正确格式化

x = 1
while x < 10:
    x += x
print(x)

为我打印的输出为16。

2 个答案:

答案 0 :(得分:2)

这对我来说很有意义。语句x += x相当于x *= 2,是x的两倍。

为帮助您理解,请尝试在每次迭代后打印x

x = 1
while x < 10:
    x += x
    print(x)

输出:

2
4
8
16

在每个步骤上:

2    # greater than 10? no
4    # greater than 10? no
8    # greater than 10? no
16   # greater than 10? yes, stop loop

答案 1 :(得分:0)

也许更改print(x)的位置可以为您提供帮助:

x = 1
print(1)
while x < 10:
    x += x
    print(x)

输出:

1
2
4
8
16

如您所见,有一个共同的顾客。 while的每次迭代都复制x的before值(这归因于x += x,它可以解释为x的两倍)。

然后,条件while x < 10非常简单。

1     # Less than 10. Keep looping.
2     # Less than 10. Keep looping.
4     # Less than 10. Keep looping.
8     # Less than 10. Keep looping.
16    # Greater than 10. STOP!
相关问题