[英]Python Code Understanding the code step by step
大家好,我目前正在練習解釋代碼並寫下代碼的過程! 這是我目前想出的。
x = 4
y = 19
finished = False
while x <= y and not finished:
subtotal = 0
for z in range(0, x, 4):
print(x)
subtotal += x
print("This is subtotal", subtotal)
if y // x <= 1:
finished = True
else:
x += x
print("New x value:", x)
我相信我在這里所做的是正確的,但是我不確定小計將如何從4變為8到24? 如果有人可以向我解釋這一點,那就太好了。
我知道范圍是互斥的,因此當x值為4時,它僅通過for循環一次,因此為什么小計=4。但是,當x值為8時,它通過for循環到達我的站立次數2次,因此是我迷路的部分。
我的最后一個問題是,每次經過此循環時,每次x值更改時,小計都會重置嗎? 這是我無法獲得正確小計的原因嗎?
如果有人可以直觀地向我展示或解釋這一點,那就太好了,謝謝!
這是因為在第一回路小計為0。 for
循環迭代僅僅一次,因為它然后看起來像這樣for z in range(0, 4, 4)
然后x和小計變成4。現在小計回到0,for循環成為for z in range(0, 8, 4)
因此for循環將迭代兩次,因為該范圍內有兩個可能的數字(分別是0和4),小計被添加到x的8和x變成16的for循環中(請注意小計不會被帶回到0,因為subtotal = 0
語句不在for循環內)現在小計8 + 16,即24。
只需檢查變量的更改:
Start: x = 4, y = 19, finished = False
1. subtotal = 0
2. z = 0
3. subtotal += x (0+4) = 4
4. x += x (4+4) = 8
5. subtotal = 0
6. z = 0
7. subtotal += x (0+8) = 8
8. x += x (8+8) = 16
9. z = 4
10. subtotal += x (8+16) = 24
11. finished = True
End: x = 16, y = 19, finished = True, z = 4, subtotal = 24
subtotal
僅在內部循環退出時重置為0
,因為x
變大,內部循環重復多次,第一次重復1
次,第二次重復2
次。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.