You need to enable JavaScript to run this app. Python自定义函数内定义的变量外部调用提示未定义错误如何解决
优惠活动
大模型
产品
解决方案
定价
更多

Python自定义函数内定义的变量外部调用提示未定义错误如何解决

问题成因

Python有严格的变量作用域规则:函数内部定义的普通变量属于局部变量,仅在函数运行周期内有效,作用域被限制在函数内部,函数执行完成后局部变量会被自动销毁,外部作用域无法直接访问。
你在getUserInput()函数内部定义了playerSolInt,但没有将该值传递到函数外部,while循环的判断逻辑尝试访问该变量时,就会触发「变量未定义」的报错。
你之前在全局初始化变量的操作没有生效,是因为如果没有用global关键字声明,函数内部对同名变量的赋值操作本质是创建了一个新的局部变量,不会修改全局同名变量的值,全局变量和函数内部的局部变量本质是两个完全独立的变量。

修复方案

最推荐的实现方式是修改函数逻辑,将用户输入转换后的结果作为返回值输出,调用函数时用变量接收返回值即可,这种方式避免了滥用全局变量,代码可维护性更高。
修复后的完整代码如下:

# Import module
import random
random.seed()

# (Random) values and calculation
firstValue = random.randint(1,10)
secondValue = random.randint(1,10)
sol = firstValue + secondValue

# 函数增加return语句返回转换后的输入值
def getUserInput():
    print("--- Please solve:", firstValue, "+", secondValue, "---")
    playerSol = input()
    playerSolInt = int(playerSol)
    return playerSolInt

counter = 0
falseAnswer = True

while falseAnswer:
    counter += 1
    try:
       # 调用函数时用变量接收返回的结果
       playerSolInt = getUserInput()
    except: 
        print("--- You did not enter a number. ---")
        continue

    if sol == playerSolInt:
        print("--- Correct answer! ---")
        falseAnswer = False
    else:
        print("--- False answer! ---")

print("--- You tried", counter, "times in total. ---")
print("*** Program has stopped ***")

内容的提问来源于stack exchange,提问作者Tolga T.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 01:06:02