Understanding Global Variables and the global Keyword in Python
This article explains Python's variable scope rules, demonstrates how local variables shadow globals, and shows how the global keyword enables functions to modify global variables, illustrated with clear examples and visual results.
I haven't used Python for a while and realized I've forgotten many of the syntax rules I previously learned; the lack of systematic practice made it hard to recall them fluently.
To achieve flexible use of Python, one should not only be able to write code but also integrate learning, doing, and teaching—learning through doing, teaching while doing, and teaching to reinforce learning.
Scope of Global Variables:
Variables defined outside a function are global, while those defined inside a function are local. Global variables are accessible in all scopes, whereas local variables are only usable within their defining function. When a name exists in both scopes, the local variable takes precedence.
global keyword:
To solve the problem of using global variables inside functions, Python provides the global keyword, which can be used to explicitly declare a variable as global.
The effect of the global keyword is to declare that a variable (e.g., var ) is global.
Example 1: Assignment inside a function cannot change a global variable's value
Result:
It can be seen that assigning a value inside the function does not change the global variable, so the global keyword is needed.
Example 2: Changing a global variable's value requires the global keyword
Test result:
The demonstration shows that a global variable's value can only be changed when the global keyword is used; otherwise the assignment creates a new local variable. This point should be remembered.
- END -
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.