如何用函数精简答题游戏重复if语句,提升代码效率?
用函数精简重复的答题逻辑
你可以把重复的答题逻辑封装成一个可复用的函数,只需要把每次变化的内容(问题文本、正确答案)作为参数传入即可。这样9道题只需要调用9次函数,不用重复写相同的if判断和输入处理代码。
步骤1:定义通用的答题函数
这个函数需要接收问题文本、正确答案和当前分数三个核心参数,内部处理输入、大小写转换、对错判断,并返回更新后的分数(Python中整数是不可变类型,返回新分数更稳妥)。
def ask_question(question_text, correct_answer, current_score): # 获取用户输入并统一大小写格式 user_answer = input(question_text).title() # 判断答案是否正确 if user_answer == correct_answer.title(): new_score = current_score + 1 print(f"Correct, your score is {new_score}!") else: new_score = current_score print(f"Unfortunately this is incorrect! Your score is {new_score}.") # 返回更新后的分数 return new_score
步骤2:调用函数处理9道题
初始化分数后,你可以选择逐个调用函数,或者用循环批量处理,两种方式都能大幅精简代码:
方式1:逐个调用(适合题目/答案无规律的情况)
score = 0 # 第1题 score = ask_question(listQuestions[0], "Quentin Tarantino", score) # 第2题 score = ask_question(listQuestions[1], "Steven Spielberg", score) # ... 以此类推,直到第9题
方式2:循环批量处理(推荐,更简洁)
如果把题目和对应答案整理成元组列表,就能用循环自动处理所有题目:
# 整理题目与答案的对应关系 quiz_items = [ (listQuestions[0], "Quentin Tarantino"), (listQuestions[1], "Steven Spielberg"), # ... 补充剩下的7道题 ] score = 0 for question, answer in quiz_items: score = ask_question(question, answer, score)
补充说明
- 修正了原代码里的拼写错误:
Unfortanetely→Unfortunately - 用f-string替代字符串拼接,输出代码更简洁易读
- 对正确答案也做了
.title()处理,避免因大小写不一致导致的判断误差
内容的提问来源于stack exchange,提问作者Kyle
相关产品推荐
相关产品推荐

