繁体   English   中英

具有不同功能的全局变量问题(使用Python)

[英]Global variable Issues with different functions (using Python)

我正在尝试创建一个程序,允许我在程序的其他功能中使用列表“用户”。 我尝试了参数,将其声明为“全局”(尽管有人告诉我这样做是不好的做法),并且我尝试研究“类”并将其全部实施都无济于事。 我还尝试将用户放入文本文件中,然后从中读取内容,但这很麻烦,因为我需要将其包含在列表中。 这是我的代码:

def register():
    global username
    username = raw_input("Enter a username: ").lower()
    firstName = raw_input("Enter your first name: ").lower()
    surname = raw_input("Enter your surname: ").lower()
    age = raw_input("Enter your age: ")
    yearGroup = raw_input("Enter your year group: ")
    users =[[firstName, surname, age, yearGroup]] 

def resultsFunction(): 
    score = 5
    results = [[score, username]]
    results.extend(users)

我努力了:

def register():
    global username
    username = raw_input("Enter a username: ").lower()
    firstName = raw_input("Enter your first name: ").lower()
    surname = raw_input("Enter your surname: ").lower()
    age = raw_input("Enter your age: ")
    yearGroup = raw_input("Enter your year group: ")
  global users 
    users =[[firstName, surname, age, yearGroup]] 

它引发错误:

    results.extend(userDetails)
NameError: global name 'userDetails' is not defined

奇怪的是,在声明用户名'global'之后(是的,我知道我不应该,但是它起作用了),我能够在函数中使用用户名,但是当我尝试使用其他变量(例如firstName)时,可以尝试仅在“ resultsFunction”中创建列表,但无法使用。

如果用户决定不进行注册,则注册功能不会一直运行,但是我无法更改它,因为我不希望用户必须始终输入其详细信息。

我很困惑,尝试了我所知道的一切。 我来这里是最后的选择,所以我希望有人可以提供帮助,也许这个问题可以帮助其他在局部和全局变量范围上遇到相同困难的人。

在函数内编写global users以更改users变量中的值。 否则,您只能读取它,而不能更改其中的值。

lis = []
def a():
    lis = [1,2]
a()
print(lis)

将打印[]

如:

lis = []
def a():
    global lis
    lis = [1,2]
a()
print(lis)

将打印[1,2]

根据我的理解,请参考您的程序。这可能会有所帮助。

username = ''
user = []
def register():
    global username
    global users
    username = input("Enter a username: ").lower()
    firstName = input("Enter your first name: ").lower()
    surname = input("Enter your surname: ").lower()
    age = input("Enter your age: ")
    yearGroup = input("Enter your year group: ")
    users =[[firstName, surname, age, yearGroup]]
def resultsFunction(): 
    score = 5
    results = [[score, username]]
    results.extend(users)
    print(results)
register()
resultsFunction()

将输出:-

Enter a username: Foo
Enter your first name: Bar
Enter your surname: Baz
Enter your age: 00
Enter your year group: 00
[[5, 'foo'], ['bar', 'baz', '00', '00']]

暂无
暂无

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

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