簡體   English   中英

Python while循環無法正常工作

[英]Python while loop does not work properly

我在if / else條件中使用while循環。 由於某種原因,在某種情況下,while循環不起作用。 條件顯示在下面的代碼中。 在這種情況下我會假設else條件應利用和weightmax_speed應該直到兩個下降while條件是不再有效。 我究竟做錯了什么?

weight = 0
max_speed = 15

if weight == 0 and max_speed <= 10:
    while weight == 0 and max_speed <= 10:
        weight=weight+1
        print(weight)
        print(max_speed)
else:
    while weight != 0 and max_speed > 10:
        weight = weight-1
        max_speed=max_speed-1
        print(weight)
        print(max_speed)

我認為您對orand感到困惑。

and表示如果兩個條件都滿足,則表達式將為True 滿足or滿足任何條件的地方。

現在根據您的代碼:

weight = 0
max_speed = 15

if weight == 0 and max_speed <= 10:
    # Goes to else block since max_speed = 15 which is >10
else:
    # This while won't be executed since weight = 0
    while weight != 0 and max_speed > 10:

假設您需要weight=0max_speed=10 你可以做到->

weight = 0
max_speed = 15

while weight !=0 or max_speed > 10:
    if weight>0: 
        weight = weight-1
    else:  
        weight = weight+1
    if max_speed>10:
        max_speed=max_speed-1
    print("{} {}".format(weight, max_speed))

您的輸出看起來像->

1 14
0 13
1 12
0 11
1 10
0 10

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM