[英]Why is this the output for the following code?
I am having trouble understanding why the output for this code is 16. I apologize if I am formatting anything incorrectly, I am new to coding. 我在理解为什么此代码的输出为16时遇到了麻烦。如果我格式化不正确,我很抱歉,我是编码新手。
I have written the code a couple times to make sure I was formatting it correctly 我已经编写了几次代码,以确保正确格式化了代码
x = 1
while x < 10:
x += x
print(x)
The output that is printing for me is 16. 对我来说输出的输出是16。
It makes sense to me. 对于我,这说得通。 The statement
x += x
is equivalent to x *= 2
, doubling x
. 语句
x += x
相当于x *= 2
,倍增x
。
To help you understand, try printing x
after every iteration: 为了帮助您理解,请尝试在每次迭代后打印
x
:
x = 1
while x < 10:
x += x
print(x)
Output: 输出:
2
4
8
16
On each step: 在每个步骤上:
2 # greater than 10? no
4 # greater than 10? no
8 # greater than 10? no
16 # greater than 10? yes, stop loop
Maybe changing the location of the print(x)
could help you: 也许更改
print(x)
位置print(x)
可以帮助您:
x = 1
print(1)
while x < 10:
x += x
print(x)
Output: 输出:
1
2
4
8
16
As you can see there is a common patron. 如您所见,有一个普通的顾客。 Each iteration of the
while
duplicates the before value of x
(that is due to x += x
, which could be interpreted as double the x). while
每次迭代都复制x
的before值(这是由于x += x
,这可以解释为x的两倍)。
Then, the condition while x < 10
is quite simple. 那么,
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!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.