我嘗試了標準的“猜亂數游戲”作為我在 python 中的第一個小專案,并決定稍微改進一下。我的目標是通過用戶輸入使程式對 ValueError 崩潰具有彈性,同時使其盡可能靈活(我微薄的技能)。我遇到了 input() 函式只回傳字串的問題,而我的具有多級例外的解決方案看起來非常笨拙和冗長。
我有這個函式詢問用戶他們想要多少猜測并回傳答案。
def guess_max_asker():
while True:
guess_max_temp = input("How many guesses do you want? (1 - 10)\n> ")
try: # lvl 1 checks if input is a valid int
guess_max_temp2 = int(guess_max_temp) #ugly
if 11 > guess_max_temp2 > 0:
print(f"Ok! You get {guess_max_temp2} tries!")
return guess_max_temp2
else:
print("That's not a valid number..")
continue
except ValueError:
print("ValueError!") # It's alive!
try: # lvl 2 checks if input is float that can be rounded
guess_max_temp2 = float(guess_max_temp)
print(f"I asked for an integer, so I'll just round that for you..")
return round(guess_max_temp2)
except ValueError: # lvl 3 checks if input is a valid string that can be salvaged
emergency_numbers_dict = {"one": 1, "two": 2, "three": 3, "four": 4, "five": 5,
"six": 6, "seven": 7, "eight": 8, "nine": 9, "ten": 10}
if guess_max_temp.lower() in emergency_numbers_dict:
print(f'I asked for an integer, but I will let "{guess_max_temp}" count..')
return emergency_numbers_dict[guess_max_temp]
else:
print("That's not a valid answer..")
continue
guess_max = guess_max_asker()
有沒有比“while True”回圈更優雅的方法?我嘗試并未能找到一種方法讓 Python 重新運行一個簡單的 if 陳述句,類似于使用“while”回圈的“continue”。如果我可以讓 Python 將輸入識別為不同的型別,我可以使用 isinstance(),但我不知道如何。我確信答案是顯而易見的,但相信我,我已經嘗試過了。
uj5u.com熱心網友回復:
“回圈嘗試/排除”方法是非常標準的,所以你走在正確的軌道上。
您可以使用以下輔助函式對其進行清理:
def input_int(prompt):
while True:
response = input(prompt)
try:
return int(response)
except ValueError:
print("ValueError -- try again")
然后你可以使用它:
user_int = input_int("Input an integer: ")
print("Accepted: ", user_int)
例子:
輸入一個整數:c ValueError -- 再試一次 輸入一個整數:1.2 ValueError -- 再試一次 輸入一個整數:1 接受:1
uj5u.com熱心網友回復:
盡可能堅持您的原始代碼,您可以嘗試:
def guess_max_asker():
while True:
guess_max_temp = input("How many guesses do you want? (1 - 10)\n> ")
if guess_max_temp.isnumeric():
if int(guess_max_temp)>11:
print("That's not a valid number")
else:
return int(guess_max_temp)
else:
emergency_numbers_dict = {"one": 1, "two": 2, "three": 3, "four": 4, "five": 5,
"six": 6, "seven": 7, "eight": 8, "nine": 9, "ten": 10}
if guess_max_temp not in emergency_numbers_dict:
print("That's not a valid answer..")
else:
print(f'I asked for an integer, but I will let "{guess_max_temp}" count..')
return emergency_numbers_dict[guess_max_temp]
guess_max = guess_max_asker()
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/454581.html
標籤:Python python-3.x 字典 类型 尝试除外
上一篇:使用Python字典模擬帶有默認情況的switch陳述句
下一篇:連接地圖中的所有欄位
