Variable Tips
Learn how local and global variables play an important role with respect to safety in Python code.
Understand local variables
Many things are confusing in Python, but few are as confusing as local and global variables. The scope of a local variable is restricted to the enclosing function but the scope of a global variable isn’t. What makes a variable local or global?
A variable is local in a function if it’s declared inside it, unless explicitly marked as global
in the same function. Because the only way to declare a variable in Python is to use it on the left-hand side (LHS) of an assignment statement, Python variables are always initialized. Whether or not a variable in a function is global, doesn’t depend on whether a global variable with the same identifier already exists. If it does, the function may have a local variable with the same name that will shadow the global variable, making it invisible in the function.
Let gv = 1
be a global variable. The variable remains global in the following two functions.
-
f1()
treatsgv
as a global because it is marked as global, despite the assignment statement. -
f2()
treatsgv
as a global because there is no assignment statement.
Let’s try the code below.
Get hands-on with 1400+ tech skills courses.