简体   繁体   English

Python-全局变量斗争

[英]Python - Global variable struggle

It might be rediculous but I couldn't get my head around the use of global variables in Python. 可能有点冗长,但我无法理解在Python中使用全局变量的情况。 It throws me syntax errors for the use of the keyword 使用关键字会引发语法错误

global

even though, I looked it up exactly that way in the documentation. 即使,我在文档中也是如此。

I know the code is clumsy for its repetative use of global variables. 我知道代码重复使用全局变量很笨拙。 Anyway, how to use them correctly? 无论如何,如何正确使用它们?

import random

r_list = []

my_list =[3,4,45,7,23,33]
match_list=[]
iteration = 0
number_matches = 0

def fill_random_list():
    for i in range(7):
        # print (random.randint(1,49))
        r_list.append(random.randint(1,49))


def return_matches(lista, listb):
    # print set(lista).intersection(listb)
    return set(lista).intersection(listb)


def return_number_matches(l_matches):
    if l_matches:
        return len(l_matches)


def draw_lottery():
    while global number_matches  < 5:'''
                                     File "C:/Lottery.py", line 27
                                     while global number_matches  < 5:
                                                ^
                                     SyntaxError: invalid syntax'''
        global r_list = []
        global match_list = []
        fill_random_list()
        match_list=return_matches(r_list, my_list)
        global number_matches=(return_number_matches(global match_list))
        global iteration+=1
        if number_matches > 4:
            print (str(global iteration) + ';' + str(global number_matches))


def iterate(number):
    for i in enumerate(range(number),1):
        print('Round: ' + str(i[0]))
        draw_lottery()


def main():
    iterate(10)


if __name__ == "__main__":
    main()

Don't annotate every use of a global variable with global . 不要注释每次使用同一个全局变量的global All you need to do is write global var1, var2 in your function before modifying the variables. 您需要做的就是在修改变量之前在函数中编写global var1, var2

If you're only reading from them you don't need to use global . 如果您只是从他们那里读取信息,则无需使用global You only need it if you're assigning to them. 仅在分配给他们时才需要它。

def draw_lottery():
    global number_matches, r_list, match_list, number_matches, iteration

    while number_matches < 5:
        r_list     = []
        match_list = []

        fill_random_list()

        match_list     = return_matches(r_list, my_list)
        number_matches = return_number_matches(match_list)

        iteration += 1

        if number_matches > 4:
            print(str(iteration) + ';' + str(number_matches))

As a matter of good style, avoid using global variables. 作为一种好的样式,请避免使用全局变量。 It's hard to keep track of program state when many functions share the same variables. 当许多函数共享相同的变量时,很难跟踪程序状态。 It's better to use parameters and return values instead, whenever possible. 最好尽可能使用参数并return值。

the problem with your code is quite simple if you want to modify a global variable inside a function you need first to refer to it explicitly, how? 如果要在函数中修改全局变量,需要先明确引用它,代码的问题非常简单。 be including the line 包括线

global variable_name

in your function code, this should occur before reading or modifying this variable 在您的功能代码中,这应该在读取或修改此变量之前发生

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

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