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

Python函数返回值未接收引发UnboundLocalError错误求助

问题分析与修复方案

你遇到的UnboundLocalError: local variable 'q_count' referenced before assignment错误,核心原因是:random_question()函数中未声明q_count为全局变量,Python会默认将其视为局部变量,但你在赋值前就直接引用了它;同时原代码里还存在字符串与数字运算、无效代码等小问题。

以下是两种修复方案,推荐第二种更简洁的写法:


方案一:修复全局变量用法

在random_question()开头声明q_count为全局变量,并修正字符串转整数的问题:

import random

# 假设已定义以下依赖内容
questions_list = ["问题1", "问题2", "问题3", "问题4", "问题5"]
def check_submitted_answers(answer):
    pass

def random_question():
    global q_count  # 声明使用全局变量q_count
    check_question_count()
    q_index = 1
    global saved_question_count
    saved_question_count = int(q_count)
    print('Awesome! you will be asked ', saved_question_count,' randomly selected questions out of the total of 15 questions available.')
    
    # 使用整数类型的q_count进行循环
    q_count_int = saved_question_count
    while q_count_int != 0:
       b = len(questions_list) - 1
       rand_num = random.randint(0,b)
       global selected_question
       selected_question = questions_list[rand_num]
       print('\n')
       print(q_index,'.',selected_question)
       global user_answer
       user_answer = input('Your answer is: ').capitalize()
       check_submitted_answers(user_answer)
       questions_list.remove(selected_question)
       q_count_int -= 1
       q_index += 1

# 验证题目数量输入的函数
def check_question_count():
        global q_count
        q_count = input('\nHow many questions do you like to take? You can choose a number between 1 to 15: ')
        while True:
          if q_count not in ['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15']:
            print('Error: Invalid input! Please type in only a number between 1 and 15: ')
            q_count = input('\nHow many questions do you like to take? You can choose a number between 1 to 15: ')
            continue
          else:
            return q_count

random_question()

方案二:移除全局变量(推荐)

全局变量会增加代码耦合度,更合理的方式是通过函数返回值传递数据,代码更简洁易维护:

import random

# 假设已定义以下依赖内容
questions_list = ["问题1", "问题2", "问题3", "问题4", "问题5"]
def check_submitted_answers(answer):
    pass

def random_question():
    # 直接接收check_question_count的返回值
    q_count = check_question_count()
    q_count_int = int(q_count)
    q_index = 1
    print('Awesome! you will be asked ', q_count_int,' randomly selected questions out of the total of 15 questions available.')
    
    while q_count_int != 0:
       b = len(questions_list) - 1
       rand_num = random.randint(0,b)
       selected_question = questions_list[rand_num]
       print('\n')
       print(q_index,'.',selected_question)
       user_answer = input('Your answer is: ').capitalize()
       check_submitted_answers(user_answer)
       questions_list.remove(selected_question)
       q_count_int -= 1
       q_index += 1

# 验证题目数量输入的函数
def check_question_count():
        while True:
          q_count = input('\nHow many questions do you like to take? You can choose a number between 1 to 15: ')
          if q_count not in ['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15']:
            print('Error: Invalid input! Please type in only a number between 1 and 15: ')
            continue
          else:
            return q_count

random_question()

额外修正的小问题:

  • 将无效的print(' ')改为print('\n')(正确的换行转义写法)
  • 删除了无意义的questions_list = questions_list代码
  • 统一使用整数类型进行循环条件判断,避免字符串与数字比较的潜在问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 05:15:46