我想每次輸入一個新數字,它將再次比較當前變數的整數,但也保存在原始變數之上,以便我可以輸入另一個數字再次比較。
我不確定為什么我不能用我輸入的變數更新當前變數。我將如何實作這一點。
我目前的代碼是:
print("give the first number: ", end = "")
g = input()
x = int(g)
finished = False
while not finished:
print("enter the next number: ", end = "")
k = input()
h = int(k)
if h == x and h != 0:
print("same")
elif h > x and h != 0:
print("up")
elif h < x and h != 0:
print("Down")
elif h != 0:
h = x
else:
h == 0
finished = True
如果程式正常作業,它看起來像這樣:
Enter the first number: 9
Enter the next number (0 to finish): 9
Same
Enter the next number (0 to finish): 8
Down
Enter the next number (0 to finish): 5
Down
Enter the next number (0 to finish): 10
Up
Enter the next number (0 to finish): 10
Same
Enter the next number (0 to finish): 0
每個條目都應替換下一個條目將與之進行比較的變數。任何幫助,將不勝感激。謝謝!
uj5u.com熱心網友回復:
您必須更新x變數,而不是那個h。此外,我修復了代碼中的其他問題(見評論)
print("give the first number: ", end = "")
g = input()
x = int(g)
finished = False
while not finished:
print("enter the next number: ", end = "")
k = input()
h = int(k)
if h == 0:
# Priority to the finish condition
finished = True
elif h == x:
# No need to check that h != 0 because it's in the elsif
print("same")
elif h > x:
print("up")
elif h < x:
print("Down")
# Update the x variable, regardless of conditions.
x = h
這給出了您期望的輸出。
give the first number: 9
enter the next number: 9
same
enter the next number: 8
Down
enter the next number: 5
Down
enter the next number: 10
up
enter the next number: 10
same
enter the next number: 0
uj5u.com熱心網友回復:
您必須在 if 回圈之外對其進行更新。所以代替這個
elif h != 0:
h = x
您可以在回圈之外執行此操作,h = x但無需 if 陳述句。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/511281.html
下一篇:在序言中使用變數設定聯合
