Python测验应用如何从列表15道题中选10道作答,答对进入下一阶段
实现步骤
- 导入Python内置
random模块,使用其中的sample方法从15道总题库中随机抽取10道不重复的题目 - 调整测试运行函数的逻辑,在用户顺利答完10道题(无答错中断)时,触发下一阶段的入口
- 修正原代码中少量语法和体验问题
修改后完整可运行代码
QuestionE.py(无改动)
class QuestionE: def __init__(self,prompt,answer): self.prompt = prompt self.answer = answer
Main.py
import random from QuestionE import QuestionE #15道题库 QE = ["I ______ tennis every Sunday morning\na. playing\nb. play\nc. am playing\nd. am play\n答案: ", "___________ is she? She's my friend from London.\na. Who\nb. Why\nc. Which\nd. What\n答案: ", "The baby _________ every night.\na. cries\nb. is crying\nc. cried\nd. cry\n答案: ", "_________ many times every winter in Frankfurt.\na. It snows\nb. It snowed\c. It is snowing\d. It is snow\n答案: ", "There ________ many flowers in the vase.\na. are\nb. have\c. has\d. is\n答案: ", "You have six flowers. Give _______ one, please.\na. you\nb. she\c. me\d. he\n答案: ", "Nid and Pon ________ go to the movie next Sunday.\na. are\nb. will\c. is\d. have\n答案: ", "Chai ________ English every day.\na. speak\b. is speaking\c. speaks\d. spoke\n答案: ", "We have lunch ________ half past five.\na. of\nb. on\c. in\d. at\n答案: ", "A week ________ seven days.\na. has\nb. have\c. are\d. is\n答案: ", "We ________ throw litter on the ground.\na. isn't\b. don't\c. aren't\d. haven't\n答案: ", "Weather report: It's seven o'clock in Frankfurt and ________\na. there is snow\b. it's snowing\c. it snows\d. it snowed\n答案: ", "Jane ________ her blue jeans today, but usually she wears a skirt or a dress.\na. wears\b. wearing\c. wear\d. is wearing\n答案: ", "I think I ________ a new calculator. This one does not work properly any more.\na. needs\b. needed\c. need\d. am needing\n答案: ", "I've just finished reading a story called Dangerous Game. It's about a man who ________ his wife because he doesn't want to lose her.\na. kills\b. killed\c. kill\d. is killing\n答案: "] # 生成总题库 questions = [ QuestionE(QE[0], "b"), QuestionE(QE[1], "a"), QuestionE(QE[2], "a"), QuestionE(QE[3], "a"), QuestionE(QE[4], "a"), QuestionE(QE[5], "c"), QuestionE(QE[6], "b"), QuestionE(QE[7], "c"), QuestionE(QE[8], "d"), QuestionE(QE[9], "a"), QuestionE(QE[10], "b"), QuestionE(QE[11], "b"), QuestionE(QE[12], "d"), QuestionE(QE[13], "c"), QuestionE(QE[14], "a"), ] def run_test(questions): score = 0 for question in questions: answer = input(question.prompt).strip() # 加strip去除用户输入的首尾空格避免误判 if answer == question.answer: score += 1 print("回答正确") else: print("回答错误") print (f"你的得分是 {score}/10") print("挑战失败,你未通过简易难度测试") break # 循环正常结束说明没有答错中断,10题全对 else: print(f"恭喜你全部答对,得分 {score}/10") print("正在进入测验下一阶段...") # 这里写你下一阶段的调用逻辑即可 # 随机抽取10道题 selected_questions = random.sample(questions, 10) run_test(selected_questions)
核心说明
random.sample(源列表, 抽取数量)会返回一个包含指定数量不重复元素的新列表,每次运行都会随机抽题,符合测验类应用的需求- for循环附带的else分支只有在循环没有被break中断时才会执行,刚好用来判断用户是否全部答对
- 新增的
strip()方法会自动去除用户输入前后的空格、换行符,避免因为输入时多打了空格导致被判错
内容的提问来源于stack exchange,提问作者candy mincy
相关产品推荐
相关产品推荐

