如何让Python(Replit)测验程序同时识别大小写字母为正确答案?
解决Python测验程序大小写不敏感的问题
你的问题出在调用字符串方法时少加了括号——.lower只是引用方法本身,没有执行转换操作,必须用.lower()才能得到转换后的小写字符串。
只需要修改run_quiz函数里的答案处理逻辑,把用户输入的答案转成小写,再和预设答案的小写版本对比,就能实现大小写不敏感的判断:
def run_quiz(questions): score = 0 for question in questions: # 将输入转成小写,同时去除可能的首尾空格 answer = input(question.prompt).strip().lower() # 把预设答案也转成小写,确保匹配不受大小写影响 if answer == question.answer.lower(): score += 1 print("You got " + str(score) + "/" + str(len(questions)) + " Correct!")
另外加上.strip()还能处理用户输入时不小心多打空格的情况,提升程序的鲁棒性。
修改后的完整代码如下:
class Question: def __init__(self,prompt,answer): self.prompt = prompt self.answer = answer # 定义问题 question_prompts =[ "Who did Echo fall in love with?\n(a) Poseidon\n(b) Zeus\n(c) Narcissus\n(d) Aphrodite ", "What did the nymphs find instead of Narcissus' body?\n(a) A dog\n(b) A flower\n(c) A hand\n(d) A pile of hair ", "Who cursed Echo?\n(a) Athena\n(b) Hades\n(c) Hercules\n(d) Hera ", "Where was the place Echo found to live in?\n(a) A cave\n(b) A palace\n(c) A cottage\n(d) A forest ", "Where did Narcissus live?\n(a) A dessert\n(b) A jungle\n(c) A house\n(d) A forest ", "What was the last thing that was left of Echo?\n(a) Her voice\n(b) Her Ears\n(c) Her Mouth\n(d) Her Nose ", "What type of nymph was Echo?\n(a) A grass nymph\n(b) A wood nymph\n(c) A water nymph\n(d) An ice nymph ", "What was Narcissus hunting when Echo first saw him?\n(a) Rabbit\n(b) Bird\n(c) Fish\n(d) Deer ", "What did Narcissus fall in love with?\n(a) Echo\n(b) A deer\n(c) His own reflection\n(d) Echo's reflection ", "What was Narcissus's last word?\n(a) Hate\n(b) Love\n(c) Happiness\n(d) Sadness " ] # 设置问题与对应答案 questions = [ Question(question_prompts[0], "c"), Question(question_prompts[1], "b"), Question(question_prompts[2], "d"), Question(question_prompts[3], "a"), Question(question_prompts[4], "d"), Question(question_prompts[5], "a"), Question(question_prompts[6], "b"), Question(question_prompts[7], "d"), Question(question_prompts[8], "c"), Question(question_prompts[9], "b") ] # 运行测验并计算得分 def run_quiz(questions): score = 0 for question in questions: answer = input(question.prompt).strip().lower() if answer == question.answer.lower(): score += 1 print("You got " + str(score) + "/" + str(len(questions)) + " Correct!") run_quiz(questions)
内容的提问来源于stack exchange,提问作者Kieran O'Mara
相关产品推荐
相关产品推荐

