[英]python 3: try except not working to check isalpha function
我正在嘗試檢查在輸入函數中輸入的是所有字母字符。 基本上,我想確保未輸入數字。 但是,當我鍵入數字(例如4)時,什么也不會發生。 我什至沒有看到異常錯誤。 另外,如果我鍵入“服用蜂蜜”或“開門”以外的任何內容,則不會啟動bear_room函數。 哈阿爾普。 提前致謝!
def bear_room():
print("there's a bear here")
print("the bear has a bunch of honey")
print("the fat bear is front of another door")
print("how are you going to move the bear?")
choice = str(input("(Taunt bear, take honey, open door?: "))
try:
if choice.isalnum() == False:
if choice == "take honey":
print("the bear looks at you then slaps your face off")
elif choice == "open door":
print("get the hell out")
else:
bear_room()
except Exception as e:
print(str(e))
print("numbers are not accepted")
bear_room()
bear_room()
沒有什么可以觸發異常的,因為從代碼角度來說,輸入數字是完全合法的。 它將檢查choice.isalnum(),對於某個數字將為True,然后將遞歸調用bear_room()。 您希望else部分包含異常中的打印內容,然后擺脫異常處理程序。
您在這里遇到一些問題。
首先,不要將輸入內容str
轉換為str
。 它已經作為input
的字符串input
。
其次,因為您的輸入不在try / except之外,所以您永遠不會在尋找異常的方式上引發異常。 不僅如此,如果輸入abcd1234
類的abcd1234
,也不會引發異常。 那仍然是一個有效的字符串。
獎金問題。 永遠不要捕獲公開的Exception
。 始終明確要捕獲的異常類型。 但是,您無需在此處進行嘗試/除外。 相反,只要檢查您是否具有有效的條目並繼續進行邏輯即可。
只需刪除您的try / except甚至isalnum
檢查,然后檢查輸入的字符串是否與您要查找的字符串匹配。 如果沒有,則輸出某種錯誤消息:
def bear_room():
print("there's a bear here")
print("the bear has a bunch of honey")
print("the fat bear is front of another door")
print("how are you going to move the bear?")
choice = input("(Taunt bear, take honey, open door?: ")
if choice == "take honey":
print("the bear looks at you then slaps your face off")
elif choice == "open door":
print("get the hell out")
else:
print("Invalid entry")
bear_room()
bear_room()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.