Skip to main content

Foundations of Python Programming: Functions First

Section 4.9 Global Variables

Variable names that are at the top-level, not inside any function definition, are called global variables and they have a global scope.
It is possible and syntactically valid for a function to access a global variable. However, doing so is considered bad form by nearly all programmers and should be avoided. This subsection includes some examples that illustrate the potential interactions of global and local variables. These will help you better understand variable scope. Hopefully, they will also convince you that things can get pretty confusing when you mix local and global variables, and that you really shouldn’t do it.

Note 4.9.1. Instructor’s Note.

Relying on global variables is a really bad habit to pick up, as Python is a language that lets you get away with globals pretty easily. As you move on to other languages, you’ll be in for a world of pain if you don’t learn to avoid globals. Be warned.
Look at the following, working but poor form variation of the square function.
Although the badsquare function works, it is poorly written. It illustrates an important rule about how variables are looked up in Python. First, Python looks at the variables that are defined as local variables in the function. Recall, this is the function’s local scope. If the variable name is not found in the local scope, then Python looks at the global variables, or global scope. This is the case illustrated in the code above. The variable power is not found locally in badsquare but it does exist globally. The appropriate way to write this function would be to pass power as a second parameter. Practice this by using Edit this code to rewrite the badsquare example to have a second parameter.
There is another variation on this theme of local versus global variables. Assignment statements in the local function cannot change variables defined outside the function. Consider the following CodeLens example:
Now step through the code. What do you notice about the values of variable power in the local scope compared to the variable power in the global scope?
There are two variables called power, each with a different scope: a power variable local to the function’s scope (created at line 3 inside the function), and a separate power variable that has global scope (assigned a value at line 7).
When a variable name is used on the left hand side of an assignment statement Python creates a variable that with a set scope. When a local variable has the same name as a global variable we say that the local shadows the global. A shadow means that the global variable cannot be accessed by Python because the local variable will be found first. This is another good reason not to use global variables with the same names as local variables. As you can see, it makes your code confusing and difficult to understand.
If you really want to change the value of a global variable inside a function, you can can do it by explicitly declaring the variable to be global, as in the example below. Again, you should not do this in your code. The example is here only to illustrate how scope in Python works.
To cement your understanding of these ideas even further lets look at one final example. Inside the following square function we are going to make an assignment to the parameter x in line 3. There’s no good reason to do this other than to emphasize the fact that the parameter x is a local variable. If you step through the example in codelens you will see that although x is 0 in the local variables for square, the x in the global scope remains 2. This is confusing to many beginning programmers who think that an assignment to a formal parameter will cause a change to the value of the variable that was used as the actual parameter, especially when the two share the same name. But this example demonstrates that that is clearly not how Python operates.

Note 4.9.2.

Instructor’s Counsel: Just because you can, doesn’t mean you should. Global variables exist, but, as a novice programmer, you really should not use them (except in the case of named constants).
Check your understanding

Checkpoint 4.9.3.

    What is a variable’s scope?
  • Its value
  • Value is the contents of the variable. Scope concerns where the variable is "known".
  • The range of statements in the code where a variable can be accessed.
  • Correct.
  • Its name
  • The name of a variable is just an identifier or alias. Scope concerns where the variable is "known".

Checkpoint 4.9.4.

    What is a local variable?
  • A temporary variable that is only used inside a function
  • Yes, a local variable is a temporary variable that is only known (only exists) in the function it is defined in.
  • The same as a parameter
  • While parameters may be considered local variables, functions may also define and use additional local variables.
  • Another name for any variable
  • Variables that are used outside a function are not local, but rather global variables.

Checkpoint 4.9.5.

    Can you use the same name for a local variable as a global variable?
  • Yes, and there is no reason not to.
  • While there is no problem as far as Python is concerned, it is generally considered bad style because of the potential for the programmer to get confused.
  • Yes, but it is considered bad form.
  • it is generally considered bad style because of the potential for the programmer to get confused. If you must use global variables (also generally bad form) make sure they have unique names.
  • No, it will cause an error.
  • Python manages global and local scope separately and has clear rules for how to handle variables with the same name in different scopes, so this will not cause a Python error.

Note 4.9.6.

Are there any times one should use global variables? No.
More correctly, you should not use global variables unless there is a very good reason.
The problem with with global variables is that they can easily lead to unintentional changes that propagate throughout the the entire programs. While it may make sense to change a global variable for one specific function, doing so may mess up the processing for all the other functions. Consider a function that is designed to round and display an assessment’s mark to the nearest whole percentage (78.7% becomes 79%). However, when calculating an overall course grade, we don’t use the individual assignments’ rounded marks, we use their raw, unrounded marks (you don’t ’round’ a ’rounded’ mark). So global changes to individual assessement grades would make the overall course grade incorrect. However, it might make sense to round the overall course grade (changed as a global variable) when that final overall grade is being sent to the Registrar.
An example of an appropriate use of a global variable is the use of a constant by a series of functions. In the example below, PI is a global variable (a constant) that does not need to be defined locally for each of the functions. Do note, PI is not changed within any of the functions.
from math import pi as PI
def area_circle( any_radius: float ) -> float:
    """with any length greater than zero, returns area"""
    return (PI * any_radius**2)

def circumference_circle(any_radius:float) -> float:
    """with any length greater than zero, returns circumference"""
    return (2 * PI * any_radius)

def volume_sphere(any_radius:float) -> float:
    """With any length greater than zero, returns volume"""
    return (4/3 * PI * any_radius**3)
You have attempted of activities on this page.