所以我有一個功能
def check_input(user_input, dictionary): #input from user, and dictionary of people and number
numval = int(user_input)
for name, code in dictionary.items():
if user_input == name or numval == code:
return True
我有字典
myDict = {'Mark':10, 'Harry':20, 'Richard':30}
最后我的主要代碼看起來像 thius
chosenPerson = input('What Person do you want to pick?')
checkInput = check_input(chosenPerson, my_dict)
if checkInput == True:
do something
不知道為什么我收到無效的文字錯誤
uj5u.com熱心網友回復:
如果chosenPersonperson 不是整數,您如何期望將其變成整數?
相反,使用 try-except 來防止非整數輸入。
def check_input(user_input, dictionary):
# First check the if the input is a normal name
if user_input in dictionary.keys():
return True
# Now see if the value is an integer and in the dict.
try:
# Here we're guarding against `ValueError` by
# calling `int` inside the try-except
if int(user_input) in dictionary.values():
return True
except ValueError:
# We expect this type of failure and ignore it.
pass
# We failed all the checks, so return false
return False
uj5u.com熱心網友回復:
為了簡單檢查,您可以check_input像這樣修改您的函式:
def check_input(user_input, dictionary):
if user_input in dictionary.keys(): #Check if a name
return (user_input, dictionary[user_input]) #return name and value
elif user_input in dictionary.values(): #Check if input in defined values
for k in dictionary.keys(): #Loop over all keys
if dictionary[k] == user_input: #Find key that stores required value
return (k, user_input)
else: #If not a name or a value
return False #Indicates that the user_input is neither a key nor a value
不過,以這種方式使用 dict 是相當冒險的。沒有什么可以阻止在字典中多次存盤相同的值。使用此處定義的函式,您將只能獲得其中一個鍵。如果您需要每個鍵都具有相同的名稱,則可以對其進行修改以適應,但如果您想要“正確”的鍵,則無法識別它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/369391.html
