简体   繁体   English

比较用户输入的字典中的key:value关系

[英]Comparing user input the key:value relationship in a dictionary

This program is a trivia game. 这个程序是一个琐事游戏。 I was to show the description (value) of a key:value pair. 我要显示一个key:value对的描述(值)。 Then I was the user to guess something. 然后我是用户来猜测一些东西。 If they guess the correct key for that description I want the program to go to the next description for guessing. 如果他们猜测该描述的正确键,我希望程序转到下一个描述进行猜测。 If they do not guess correctly, I want the program to give the user another guess. 如果他们猜错了,我希望程序给用户另一个猜测。

So far if they guess correctly the program works. 到目前为止,如果他们猜对了,程序就可以运行。 If the user guesses incorrectly and the guess is a wrong key, then the program works. 如果用户猜错了并且猜测是错误的密钥,则程序可以工作。 If the guess is something random like "ghghghgh" I get the "KeyError". 如果猜测是随机的,例如“ ghghghgh”,我将得到“ KeyError”。

Console: 安慰:

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 . . .

Code: 码:

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!")

if guess in fruits will tell you if the guess is in the dict or not. if guess in fruits的猜测会告诉您猜测是否在字典中。

guess = input("...")
if guess in fruits and fruits[guess] == fruit:
    print("You got it")
else:
    print("Guess again")

Or, instead of using [] to get the current item in the dict (which, as you found out, will fail if the key isn't there), you can use .get() , which returns None if the key is not found: 或者,您可以使用.get() ,而不是使用[]获取dict中的当前项(如您所发现,如果键不存在,该项将失败),而可以使用.get() ,如果键不存在则返回None发现:

if fruits.get(guess) == fruit:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM