python - 比较用户输入的 key :value relationship in a dictionary

标签 python

这个程序是一个问答游戏。我要显示键:值对的描述(值)。然后我是用户来猜测一些事情。如果他们猜出该描述的正确键,我希望程序转到下一个描述进行猜测。如果他们没有猜对,我希望程序给用户另一个猜测。

到目前为止,如果他们猜对了,程序就可以运行。如果用户猜测错误并且猜测是错误的键,则程序可以运行。如果猜测是随机的,比如“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 不存在,则会失败) .get(),如果找不到 key ,则返回 None:

if fruits.get(guess) == fruit:

关于python - 比较用户输入的 key :value relationship in a dictionary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57228706/

相关文章:

Python将日期字符串转换为python日期并减去

python - 如何检测Python中变量的更改位置?

python - 如何将None关键字作为命令行参数传递

python - 使用 Google Compute Engine 默认服务帐户签署 Google Cloud Storage URL

Python:类属性,默认为父级的值,并且可用于整个层次结构

python - 使用 BeautifulSoup 解析 HTML 和复杂的表格

python - 我想在 python 中打印 "\"字符,但我得到 "\\"

python - 使用 psycopg2 插入多词字符串和空数组

python - 枕头 python : Improve script performance

python - exception_on_overflow参数不起作用? PyAudio的