You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python测验程序报错:rand_quiz()未定义,请求代码排查与修正

修正你的随机测验程序

嘿,我来帮你搞定这个问题!你遇到的rand_quiz()函数未定义错误,核心原因是你的代码里确实没实现这个函数(虽然你提到已经定义,但给出的代码片段里没有它的影子),另外你的star_score()函数也存在全局变量使用、循环逻辑不完整的问题。我帮你把整个代码修正并补全,让它能正常运行:

修正后的完整代码

import random
import operator

operators = {
    "+": operator.add,
    "-": operator.sub,
    "*": operator.mul,
    "/": operator.truediv,
}

# 全局变量初始化
questions = 0
star = 0

def rand_quiz():
    """生成随机算术题并返回题目字符串和正确答案"""
    num1 = random.randint(1, 20)
    num2 = random.randint(1, 20)
    # 随机选择运算符,除法时确保除数不为0
    while True:
        op_symbol = random.choice(list(operators.keys()))
        if op_symbol == "/" and num2 == 0:
            num2 = random.randint(1, 20)
        else:
            break
    # 计算正确答案
    correct_answer = operators[op_symbol](num1, num2)
    # 构造题目字符串
    question_str = f"{num1} {op_symbol} {num2} = ?"
    return question_str, correct_answer

def star_score():
    global questions, star  # 声明使用全局变量
    while questions < 5:  # 循环5次(questions从0到4)
        question, answer = rand_quiz()
        print(question)
        # 获取用户输入并处理格式
        try:
            user_input = float(input("请输入你的答案:"))
            # 处理除法的精度问题,允许小误差
            if abs(user_input - answer) < 0.01:
                print("答对啦!")
                star += 1
            else:
                print(f"答错了,正确答案是{answer:.2f}")
        except ValueError:
            print("请输入有效的数字!")
        questions += 1  # 题目数加1
    # 循环结束后显示总分
    print(f"\n测验结束!你的得分是:{star}/5")

# 启动测验程序
star_score()

关键修改说明

  • 补全rand_quiz()函数:这是你报错的核心原因,现在这个函数会生成两个1-20的随机数,随机选择运算符(除法时避免除数为0),计算正确答案并返回题目和答案,确保每次都是不同的随机问题。
  • 全局变量声明:在star_score()里添加global questions, star,这样函数内部才能修改全局的计数变量,否则会被当成局部变量导致错误。
  • 完善循环逻辑:原来的while循环逻辑错误(只执行一次就return),现在改成循环5次,每次调用rand_quiz()生成新题目,处理用户输入并判断对错,更新分数。
  • 处理输入异常和精度问题:添加了try-except捕获非数字输入,除法时允许小范围的精度误差,避免因为浮点数精度问题误判正确答案。

内容的提问来源于stack exchange,提问作者user9126689

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:49:04