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

Python函数内定义的变量外部访问触发NameError报错求解

问题分析与解决

错误原因

你代码里的User和Password是test()函数内部的局部变量,函数外部的while循环无法访问这些变量,这就是触发NameError的核心原因。而且就算你调用test()输入了值,外部也拿不到这些值,循环的判断条件自然无法生效。

修复方案(推荐)

让函数返回输入的用户名和密码,在循环中接收这些值后再做判断:

def test():
    user = input("user? ")
    password = input("password? ")
    return user, password

while True:
    user, password = test()
    if user == "juu" and password == "sushi":
        print("welcome")
        break
    else:
        print("sorry but try again")

另一种方案(不推荐,使用全局变量)

通过global关键字将变量声明为全局变量,让函数内外都能访问:

def test():
    global user, password
    user = input("user? ")
    password = input("password? ")

test()
while True:
    if user == "juu" and password == "sushi":
        print("welcome")
        break
    else:
        print("sorry but try again")
        test()

注:全局变量会增加代码维护难度,非必要不建议使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 00:57:26