Python 从其他函数打印main中定义的变量

Python 从其他函数打印main中定义的变量,python,python-3.x,Python,Python 3.x,无法请求用户名字符串。 试着用两天时间解决这个问题,如果有人能帮忙,非常感谢 def theproblem(): print(username) def main(): username = "myUserName" theproblem() 您需要传入一些内容作为函数的参数: name 'username' is not defined 我理解您试图执行的操作,但由于变量是在函数中定义的,因此只能在该特定函数中访问,除非您返回变量或

无法请求用户名字符串。 试着用两天时间解决这个问题,如果有人能帮忙,非常感谢

def theproblem():
    print(username)

def main():
    username = "myUserName"
    theproblem()

您需要传入一些内容作为函数的参数:

name 'username' is not defined 





我理解您试图执行的操作,但由于变量是在函数中定义的,因此只能在该特定函数中访问,除非您返回变量或使用
全局

def theproblem(username):
    print(username)

def main():
    username = "myUserName"
    theproblem(username)

这绝对是不推荐的,因为这被认为是一种坏做法

在我看来,main()中的username是一个局部变量,所以如果我们想为另一个函数访问它,我们可以使用全局语法,如下面所示:

def theproblem():
    print(username)

def main():
    global username
    username = "myUserName"
    theproblem()
或者像这样:

def theproblem():
    print(username)
def mainFunc():
    global username
    username = "myUserName"
    theproblem()

mainFunc()

解决此问题的另一种方法(尚未提及)是嵌套函数:

def mainFunc():
    global username
    username = "myUserName"
def theproblem():
    mainFunc()
    print(username)

theproblem()

您确实需要后退一步,了解基本的作用域规则(
username
是函数的本地
main
,您可以将其设置为全局的,但这是一种不好的做法),并将值作为参数传递给函数,然后将这些值返回给调用者。继续阅读
def main():
    def theproblem():
        print(username)

    username = "myUserName"
    theproblem()

main()