如何在列表中使用.lower()

2024-10-06 12:25:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python的新手,我制作了这个问答游戏,它进行得很顺利,但我对如何修复代码中不起作用的部分感到非常困惑。 要回答代码中的问题,您必须键入a、b、c或d(其中只有一个是正确的),但当我用大写字母键入正确的字母时,它表示不正确,但当我用小写字母键入正确的字母时,它表示正确。我尝试过一些方法,例如.lower(),但我不知道如何或在哪里放置.lower()。另一个问题是我不知道如何在测验中添加轮数(例如第1轮、第2轮)。我做过研究,但什么也找不到。请帮帮我

这是密码

import random

#questions and answers
Questionnaires = {
"How many days are there in a year? \n A. 366\n B. 365\n C. 366 \n D. 363":"b",
"How many years are in a century?  \n A. 10 years \n B. 50 years \n C. 100 years \n D. 75" :"c",
"How many hours are in  a day? \n A. 24 hours \n B. 22 hours \n C. 20 hours \n D. 21 hours ":"a",
"What year is it? \n A. 2020 \n B. 2022 \n C. 2021 \n D. 2019" : "c"
}
#score counter which goes up when the user gets a question correct.   
score = 0
question = list (Questionnaires.keys())
#input answer here 
while True:
    if not question:
        break
    ques = random.choice(question)
    print(ques)
    while True:
        answer = input('Answer ' )
        # if correct, moves onto next question
        if answer == Questionnaires[ques]:
            print("Correct Answer")
            print ()
            score+=1
            print("total score is", score)
            print()
            break
        else:
            #if wrong, Asks the same question again
            print("Wrong Answer, try again")
    question.remove(ques)

  

Tags: answerin键入ifaremanyhowscore
3条回答

这很有效

if answer.lower() == Questionnaires[ques]:

为了让小写答案有效

answer = input('Answer: ').lower()

为了展示自己

round = 1
while True:
    print("Round %d" % round)
    # same codes inside while loop
    round += 1

将第34行替换为

answer = input('Answer ' ).strip().lower()

相关问题 更多 >