Unbound Local Error with global variable

前端 未结 3 1903
别跟我提以往
别跟我提以往 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条回答
  •  -上瘾入骨i
    2021-01-12 05:59

    Found that variables in main act like global "read only" variables in function. If we try to reassign the value, it will generate error.

    Try:

    #!/usr/bin/env python
    RED=1
    A=[1,2,3,4,5,6]
    
    def f():
        print A[RED]
    
    f()
    

    It's ok.

    But:

    #!/usr/bin/env python
    RED=1
    A=[1,2,3,4,5,6]
    
    def f():
        print A[RED]
        A = [1,1,1,1,1]
    
    f()
    

    Generate

      File "./test.py", line 6, in f
        print A[RED]
    UnboundLocalError: local variable **'A'** referenced before assignment
    

    and:

    #!/usr/bin/env python
    RED=1
    A=[1,2,3,4,5,6]
    
    def f():
        print A[RED]
        RED = 2
    
    f()
    

    Generate

      File "./test.py", line 6, in f
        print A[RED]
    UnboundLocalError: local variable **'RED'** referenced before assignment
    

提交回复
热议问题