[英]How to stop a while true loop using conditionals?
當發現十六進制數的用戶輸入為“停止”或“停止”時,我試圖讓我的while True
循環結束。 但是,每次我嘗試測試它時,條件永遠不會通過,而是進入第一個條件並將其視為常規數字,因此循環永遠不會結束。
我嘗試將“停止”條件移到第一個條件之上,它所做的只是給出print
語句,但保持循環運行並且試圖返回 false 也沒有停止循環。
我的條件是錯誤的還是我的邏輯?
def hex_to_words():
while True:
hex_num = input("Enter a Hex Number Watney: ")
print(hex_num)
if hex_num != "Stop" or hex_num != "stop":
if len(hex_num) <= 2:
letter = chr((int(hex_num,16)))
print(letter)
if any(x not in allowed_characters for x in letter):
print("error: invalid number")
hex_to_words()
else:
letArray.append(letter)
print(letArray)
hex_to_words()
elif len(hex_num) > 2:
print("Keep the number to two digits Watney!")
else:
print("Program shutting down...")
#return False
break
hex_to_words()
如果你一定想用遞歸來做,你需要在遞歸調用 hex_to_words() 之后中斷,否則你會中斷最里面的 function 調用,但前面調用中的 while 循環不會被中斷。 所以寫
def hex_to_words():
while True:
hex_num = input("Enter a Hex Number Watney: ")
print(hex_num)
if hex_num != "Stop" and hex_num != "stop":
if len(hex_num) <= 2:
letter = chr((int(hex_num,16)))
print(letter)
if any(x not in allowed_characters for x in letter):
print("error: invalid number")
hex_to_words()
break
else:
letArray.append(letter)
print(letArray)
hex_to_words()
break
elif len(hex_num) > 2:
print("Keep the number to two digits Watney!")
else:
print("Program shutting down...")
#return False
break
hex_to_words()
此外,按照評論中的建議更改or
更改為and
。 但是,這不需要是遞歸的 function ,事實上我認為遞歸使它不太清楚,並且可能也更慢並且更容易發生堆棧溢出。 更好的版本是簡單地刪除遞歸調用,程序將按原樣運行:
def hex_to_words():
while True:
hex_num = input("Enter a Hex Number Watney: ")
print(hex_num)
if hex_num != "Stop" and hex_num != "stop":
if len(hex_num) <= 2:
letter = chr((int(hex_num,16)))
print(letter)
if any(x not in allowed_characters for x in letter):
print("error: invalid number")
else:
letArray.append(letter)
print(letArray)
elif len(hex_num) > 2:
print("Keep the number to two digits Watney!")
else:
print("Program shutting down...")
#return False
break
hex_to_words()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.