In Python, the global keyword is used to use global variables in functions or other local scopes. There are two main reasons for using the global keyword: 1. Modify the value of global variables in a function. 2. Access global variables in functions to avoid UnboundLocalError errors. Example 1: Modify the value of a global variable
python count = 0 def add(): global count count += 1 add() print(count) # 1
If the global keyword is not used here, a local variable count will be created within the function add() and the global variable will not be modified. Example 2: Access global variables
python count = 0 def print_count(): print(count) print_count() # 0
But if you try to modify global variables in a function:
python count = 0 def add_one(): count += 1 # UnboundLocalError add_one()
At this time, the global keyword must be used:
python count = 0 def add_one(): global count count += 1 add_one() print(count) # 1
To summarize the principles of using global: - If you want to modify global variables inside a function, you need to use a global statement. - If you only access global variables without modifying them, you do not need global. - global only applies to variables, not to other objects such as constants and classes. - Using global will make the code difficult to maintain, so try to avoid using it.