这个程序是一个问答游戏。我要显示键:值对的描述(值)。然后我是用户来猜测一些事情。如果他们猜出该描述的正确键,我希望程序转到下一个描述进行猜测。如果他们没有猜对,我希望程序给用户另一个猜测。
到目前为止,如果他们猜对了,程序就可以运行。如果用户猜测错误并且猜测是错误的键,则程序可以运行。如果猜测是随机的,比如“ghghghgh”,我会得到“KeyError”。
控制台:
Tasty And Juicy
What fruit does the above sentence describe per se?gh
Traceback (most recent call last):
File "bazinga.py", line 22, in <module>
if fruits[guess] == fruit:
KeyError: 'gh'
(program exited with code: 1)
Press any key to continue . . .
代码:
fruits = {
'apple':'tasty and juicy',
'banana':'long and squishy',
'orange':'ripe and yummy'
}
# loops through the values of the dictionary fruits
for fruit in fruits.values():
print(fruit.title())
correct = False
guess = ''
# guess is base incorrect to start the while loop
# the while loop goes until the correct guess is declared
while not correct:
guess = input("\nWhat fruit does the above setence describe \
per se?")
if fruits[guess] == fruit:
print("\nWow what a big brain you got there!")
corecct = True
else:
print("Uh-oh, uh-oh! Guess a again big buy!")
最佳答案
如果猜水果
会告诉你猜测是否在字典中。
guess = input("...")
if guess in fruits and fruits[guess] == fruit:
print("You got it")
else:
print("Guess again")
或者,您可以使用 来代替使用
,如果找不到 key ,则返回 []
来获取字典中的当前项目(正如您所发现的,如果 key 不存在,则会失败) .get()None
:
if fruits.get(guess) == fruit:
关于python - 比较用户输入的 key :value relationship in a dictionary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57228706/