[英]How to use a dictionary inside of a while loop?
我正在尝试制作一个琐事游戏,这是我目前拥有的代码。 我在增加玩家在这场比赛中的得分时遇到了麻烦。 我正在使用 while 循环来尝试增加玩家分数,如果玩家 1 的问题错了,那么轮到玩家 2,但我不知道如何在两者之间切换。 我有一个“答案”变量,玩家将在其中输入值。 在这个 while 循环中,我想说的是,当“答案”等于正确答案时; 我希望您执行以下操作,当“答案”不等于答案时,请执行以下操作。 我正在尝试从我的答案字典中获取相应的值,但我不知道如何获取它。 “answers [key]”给了我一个错误,我需要输入其他内容。
player_1_points = 0
player_1 = input("Enter in your name Player 1: ")
player_2_points = 0
player_2 = input("Enter in your name Player 2: ")
questions = {'one' : 'What is the tallest mountain in the world?'}
choices = {'a' : 'A. Mount Everest', 'b' : 'B. Mount St. Helens', 'c' : 'C. Mount Vesuvius', 'd' : 'D. K2'}
answers = {1 : {'Answer': 'A'}}
print(questions['one'])
print(choices['a'], choices['b'], choices['c'], choices['d'])
answer = str(input("Answer is: "))
while answer == answers[key] :
if player_1 == answer :
player_1_points += 1
print("Correct Answer!")
print(player_1, player_1_points)
print(player_2, player_2_points)
elif player_2 == answer :
player_2_points += 1
print("Correct Answer!")
print(player_1, player_1_points)
print(player_2, player_2_points)
while answer != answer[key] :
if player_1 != answer :
print("Incorrect, Player 2's Turn")
print(answer)
elif player_2 != answer :
print("Incorrect, Player 1's turn")
print(answer)
对不起,我改变了你的代码。
player_1_points = 0
player_1 = input("Enter in your name Player 1: ")
player_2_points = 0
player_2 = input("Enter in your name Player 2: ")
# now questions is a list of dictionaries
questions = [
{
'question': 'What is the tallest mountain in the world?',
'option a': 'A. Mount Everest',
'option b': 'B. Mount St. Helens',
'option c': 'C. Mount Vesuvius',
'option d': 'D. K2',
'answer': 'A. Mount Everest'
}
]
# you can add more questions to above list of questions
# loop through list of questions
for question in questions:
print(question['question'])
print(question['option a'])
print(question['option b'])
print(question['option c'])
print(question['option d'])
# ask player 1 to enter their answer
player_1_answer = input("Enter you answer Player 1 : ")
if player_1_answer == question['answer']:
print('Correct Answer!')
player_1_points += 1
else:
print('Incorrect Answer!')
# ask player 2 to enter their answer
player_2_answer = input("Enter you answer Player 2 : ")
if player_2_answer == question['answer']:
print('Correct Answer!')
player_2_points += 1
else:
print('Incorrect Answer!')
# print scores for each player at the end
print(player_1, player_1_points)
print(player_2, player_2_points)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.