繁体   English   中英

如何在 Python 中的另一个自定义 function 中使用自定义 function 的局部变量

[英]How can I use the local variable of a self-define function in another self-def function in Python

我在 Python 中写了一个 function 的 sign_up:

def sign_up():
    print('You choose to sign up: ')
    name = input('Please input your name: ')
    phone_number = input('Please input your phone number: ')
    code1 = str(input('Please input your code: '))
    code2 = str(input('Please input your code again to make sure right: '))

    while code1 != code2:
        print('Your two times-codes are not same, just try again: ')
        code1 = str(input('Please input your code: '))
        code2 = str(input('Please input your code again to make sure right: '))

    else:
        print('You have signed up successfully. Just wait to jump to the main page....')

    customer = {'name': name, 'phone_number': phone_number, 'code': code1}
    return

如您所见,我使用了一个名为“客户”的字典来存储客户的信息。 我的麻烦是:

当我想编写 function log_in() 并且我想使用在 function sign_up() 中定义的字典“客户”来检查用户输入的信息是否与字典“客户”中的信息相同时。当我这样做时,'客户'收到错误“未解析的引用'客户'”。我该怎么做才能避免它?我应该使用全局变量吗?

提前感谢您的帮助。

问题是您的变量仅存在于本地 scope 中(在 function sign_up()中)。 最简单的方法是使您的变量全局化。

def sign_up():
    print('You choose to sign up: ')
    name = input('Please input your name: ')
    phone_number = input('Please input your phone number: ')
    code1 = str(input('Please input your code: '))
    code2 = str(input('Please input your code again to make sure right: '))

    while code1 != code2:
        print('Your two times-codes are not same, just try again: ')
        code1 = str(input('Please input your code: '))
        code2 = str(input('Please input your code again to make sure right: '))

    else:
        print('You have signed up successfully. Just wait to jump to the main page....')

    global customer
    customer = {'name': name, 'phone_number': phone_number, 'code': code1}
    return

现在您应该可以在任何地方使用customer

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM