数学测验程序始终返回0分及答错扣分功能实现咨询(编程新手)
数学测验程序问题修复与答错扣分实现
一、得分始终为0的问题原因及修复
你的程序里,input()获取的用户输入是字符串类型,但你在判断时是和整数(比如4、0)做相等比较——字符串和整数永远不会相等,所以正确答案的判断逻辑永远不会触发,score自然一直是0。
修复步骤:
- 将用户输入的字符串转换成整数,用
int()函数处理 - 可选:加入异常处理,避免用户输入非数字导致程序崩溃
修复后的完整代码:
score = 0 print('Math Quiz') def check_answer(user_input, correct_answer): global score try: # 把用户输入转为整数 user_answer = int(user_input) if user_answer == correct_answer: print("Correct answer!") score += 1 else: print('Sorry, wrong answer.') except ValueError: # 处理非数字输入的情况 print("请输入有效的数字!") question_1 = input('What is 2 times 2?\n') check_answer(question_1, 4) question_2 = input('What is 1 minus 1?\n') check_answer(question_2, 0) question_3 = input('What is 4 divided by 2?\n') check_answer(question_3, 2) question_4 = input('What is 3 to the third power?\n') check_answer(question_4, 9) question_5 = input('What is 3 times 5?\n') check_answer(question_5, 15) print(f"最终得分:{score}")
二、答错扣分功能实现
要实现答错扣分,只需要在check_answer函数的else分支里对score做减法操作,还可以设置分数下限(比如不能低于0),避免出现负分。
修改后的check_answer函数(包含扣分逻辑):
def check_answer(user_input, correct_answer): global score try: user_answer = int(user_input) if user_answer == correct_answer: print("Correct answer!") score += 1 else: print('Sorry, wrong answer.') # 答错扣1分 score -= 1 # 确保分数不低于0 if score < 0: score = 0 except ValueError: print("请输入有效的数字!") # 输入无效也扣分,可根据需求调整 score -= 1 if score < 0: score = 0
把这个函数替换到之前的代码里,就能实现答错扣分的效果了。
内容的提问来源于stack exchange,提问作者Mr.Bunberry66
相关产品推荐
相关产品推荐

