[英]Why is this the output for the following code?
我在理解為什么此代碼的輸出為16時遇到了麻煩。如果我格式化不正確,我很抱歉,我是編碼新手。
我已經編寫了幾次代碼,以確保正確格式化了代碼
x = 1
while x < 10:
x += x
print(x)
對我來說輸出的輸出是16。
對於我,這說得通。 語句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
也許更改print(x)
位置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!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.