[英]Why do I have an infinite While loop?
我正在嘗試編寫一個基本循環,但我不明白為什么它會打印一個無限循環而不是 -1 到 -24。
net_distance = 0
def go_back(distance_backwards1):
while net_distance != net_distance - distance_backwards1:
net_distance = net_distance - 1
print(net_distance)
go_back(24)
while
循環中的條件
net_distance != net_distance - distance_backwards1
是——在從兩邊減去共同項net_distance
之后——與
0 != -distance_backwards1:
即與
0 != distance_backwards1:
這意味着如果您的 function go_back()
的參數distance_backwards1
不為零,則條件仍將為True
並且 - 因此 - 您的while
循環將是無限的。
看起來你正在減少錯誤的變量。 您還需要在減少之前打印。 您的 while 循環正在減少net_distance
並且它不斷進入負值並且永遠不會達到您傳遞的值。 相反,您需要減少發送的值,使其達到net_distance
對您的代碼進行細微調整,然后向后打印。
net_distance = 0 #looks like you want to get here
def go_back(distance_backwards1):
while net_distance != distance_backwards1: #check if you got to 0
print(distance_backwards1) #print the number first
distance_backwards1 = distance_backwards1 - 1 #decrement by 1
go_back(24)
output 將是:
24
23
22
21
20
19
18
17
16
15
14
13
12
11
10
9
8
7
6
5
4
3
2
1
你可能想要
def go_back(distance_backwards1):
while distance_backwards1 > 1:
distance_backwards1 = distance_backwards1 - 1
print(-distance_backwards1)
go_back(24)
並不是說您不需要變量net_distance
。
您只需減少參數並在循環中打印其相反值(即其“減”值),僅由條件net_distance > 1
控制。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.