這個問題在這里已經有了答案: 檢查字典中是否已經存在給定的鍵 16個答案 21 小時前關閉。
使用 Python:你好,我想知道我是否能夠撰寫一個陳述句而不是十幾個 if/elif 陳述句。我的字典有 12 種武器,鍵值為 1-12。我想一定有一種方法可以做出類似于'如果選擇是1-12,然??后列印“你選擇了[正確的字典值]。下面是我當前的第一個if陳述句:
weapons = {
1: "Dagger",
2: "Long Sword",
3: "Bastard Sword"
}
print("\nWhat type of weapon do you use?")
print("Please choose from the following:\n")
for key, value in weapons.items():
print(key, ":", value)
try:
selection = int(input("\nSelect a number: "))
if selection == 1:
print("You have chosen the " weapons[1] "\n")
print("You have chosen, wisely.")
謝謝您的幫助!
uj5u.com熱心網友回復:
您可以測驗選擇是否在字典中
if selection in weapons:
...
或者,既然你有一個 try/except 塊,就抓住KeyError失敗。在這里,使用 f 字串,python 將嘗試獲取,如果它不存在weapons[selection],則會引發。KeyError同樣,對于無法轉換為 的錯誤輸入int,python 將引發ValueError. 一個 try/except 捕獲兩個錯誤。
try:
selection = int(input("\nSelect a number: "))
print(f"You have chosen the {weapons[selection]}")
print("You have chosen, wisely.")
except (KeyErrror, ValueError):
print(f"Selection '{selection}' is not valid")
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/510372.html
標籤:Python字典if 语句
下一篇:在R中使用ifelse創建新列
