Python 创建一个变量以保存用户输入的所有数据
我正在编写一个小的控制台程序,从用户那里获取值,并对它们进行迭代,然后将其显示给用户。但是我应该把从用户那里得到的所有值保存在一个变量中。以下是我可以创建的内容:Python 创建一个变量以保存用户输入的所有数据,python,Python,我正在编写一个小的控制台程序,从用户那里获取值,并对它们进行迭代,然后将其显示给用户。但是我应该把从用户那里得到的所有值保存在一个变量中。以下是我可以创建的内容: def get_options(): print('============= Intranet App ==============') print('Please, choose the activity. Enter the corresponding number.') print('1. Create
def get_options():
print('============= Intranet App ==============')
print('Please, choose the activity. Enter the corresponding number.')
print('1. Create user')
print('2. Notify users')
print('3. Quit app')
a = int(input('Option: '))
all_users = []
print('In variable you have these values', all_users)
while True:
if a == 1:
print('Please enter the user type. (i.e., student, lecturer, management)')
global user_type
user_type = input('Enter user roles:')
user_list = user_type.split()
if user_type:
print('Exiting program..')
get_options()
print(user_type, 'is created')
all_users += user_list
print(all_users)
但是当新的递归从
开始时,所有用户的值都会消失。如何将所有值保存在一个变量中,并且永远不应删除这些值?您只需将所有用户
列表设置为全局,而不是本地获取选项
。在get\u options
函数之外定义all\u users
。如果添加关键字参数并将列表传递到下面的递归层,则可以保留all\u users
列表
def get_options(all_users=None):
if all_users is None:
all_users = []
# later in the func
get_options(all_users=all_users)
在get_options()函数之外定义all_users=[],因为当递归调用get_options时,它每次都会创建所有_用户的新实例。但是变量all_user将变为全局变量,所以我不知道如何在递归中调用它。请在实际示例中演示一下?如果我将在递归外部声明变量,那么我如何才能访问递归内部的变量?嘿,Dustin,有一个你称之为LGB规则的东西。变量首先在局部范围内检查,然后在全局范围内检查,最后在内置范围内检查。