Unbound Local Error with global variable

前端 未结 3 1926
别跟我提以往
别跟我提以往 2021-01-12 05:26

I am trying to figure out why I get an UnboundLocalError in my pygame application, Table Wars. Here is a summary of what happens:

The variables, REDGOLD

3条回答
  •  [愿得一人]
    2021-01-12 06:13

    global make the global variable visible in the current code block. You only put the global statement in main, not in attack.

    ADDENDUM

    Here is an illustration of the need to use global more than once. Try this:

    RED=1
    
    def main():
        global RED
        RED += 1
        print RED
        f()
    
    def f():
        #global RED
        RED += 1
        print RED
    
    main()
    

    You will get the error UnboundLocalError: local variable 'RED' referenced before assignment.

    Now uncomment the global statement in f and it will work.

    The global declaration is active in a LEXICAL, not a DYNAMIC scope.

提交回复
热议问题