2016-09-06 210 views
0

我在if/else條件中使用while循環。出於某種原因,在一種情況下while循環不起作用。條件顯示在我的代碼下面。在這些條件下,我會假定應該使用else條件,並且應該減少weightmax_speed,直到while條件不再有效。我究竟做錯了什麼?Python 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) 
+0

用的是什麼,而在這裏循環?我不能理解它背後的邏輯。你想實現什麼目標? –

+5

它進入'else'分支,但由於weight爲'0',因此'weight!= 0'的計算結果爲'False',因此整個'weight!= 0和max_speed> 10'表達式的計算結果爲'False'。這就是爲什麼while循環不能運行的原因。 – Sevanteri

+0

你想要'weight = 0'和'max_speed = 10'嗎? – jbsu32

回答

1

假設您需要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 
1

我想你是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: 
+1

如果我使用或,代碼繼續運行,並沒有結束。 – user3200392

+0

它基於你想要達到的邏輯。我已經在我的答案中更新瞭解釋,可能會有所幫助。 –

+0

在第一個'while'循環中,您應該添加'max_speed + = 1'來更改max_speed值 –