我正在尝试建立一个格斗游戏,其中会打印一个问题,您必须正确回答问题才能赢得战斗。但是我发现我找不到找到读取随机问题的代码的方法,因此这意味着我无法读取正确的答案。
我尝试过将随机数分成多个变量,但这没有用。我也没有太多时间尝试其他任何东西。
source file
如果回答正确,则会显示“您赢了!”并且如果您回答错误,它会显示“您丢失了...”,但它无法读取打印的内容,因此始终显示“您丢失了...”
答案 0 :(得分:0)
一种好的方法是将问题和答案存储在字典中,并使用良好的变量名。
import random
fights = {"I have a bed but never sleep": "river",
"What time of day is the same fowards as it is backwards?": "noon",
"3+2": "5"}
question = random.choice(tuple(fights.keys()))
print(question )
answer = input("What shall you say?\n")
if answer == fights[question]:
print("correct")
else:
print("wrong")
如果您不想再次使用此词典,则可以改用fights.popitem()
。 请记住,如果使用Python> = 3.7 popitem
,将始终返回相同的键值对:
fights = {"I have a bed but never sleep": "river",
"What time of day is the same fowards as it is backwards?": "noon",
"3+2": "5"}
question, correct_answer = fights.popitem()
print(question)
user_answer = input("What shall you say?\n")
if user_answer == correct_answer:
print("correct")
else:
print("wrong")