Use of “global” keyword in Python

后端 未结 10 2430
既然无缘
既然无缘 2020-11-21 05:05

What I understand from reading the documentation is that Python has a separate namespace for functions, and if I want to use a global variable in that function, I need to us

10条回答
  •  无人及你
    2020-11-21 05:37

    Global makes the variable "Global"

    def out():
        global x
        x = 1
        print(x)
        return
    
    
    out()
    
    print (x)
    

    This makes 'x' act like a normal variable outside the function. If you took the global out then it would give an error since it cannot print a variable inside a function.

    def out():
         # Taking out the global will give you an error since the variable x is no longer 'global' or in other words: accessible for other commands
        x = 1
        print(x)
        return
    
    
    out()
    
    print (x)
    

提交回复
热议问题