liveBook · Manning

Global variable

As explained in Get Programming: Learn to code with Python

A global variable is a variable bound in the global scope and accessible from code whose name resolution reaches that scope.

A global variable is defined in the main program scope, also called the global scope. A function can read a global variable when its name is not found in the function’s own scope. Python searches outward through enclosing scopes until it reaches the global scope. section 22.2

Two variables with the same name

In `fairy_tale()`, `peter = 5` belongs to the function scope. The later `peter = 30` belongs to the global scope. Calling the function prints 5, while the final global `print(peter)` prints 30. The same name refers to separate variables because the variables occupy different scopes. section 22.2

Listing 22.1. Defining variables with the same name in different scopes
def fairy_tale():              #1
    peter = 5                  #2
    print(peter)               #3

peter = 30                     #4
fairy_tale()                   #5
print(peter)                   #6

Trace the function call and compare the function-scoped `peter` with the global `peter`. section 22.2

Keep these rules in mind:

  • A function may access a global variable without defining a same-named variable locally. section 22.2
  • Assigning to a name inside a function does not modify the global variable as shown; the function must define its own variable first, or the operation produces an error. section 22.2
  • A local variable can temporarily hide a global variable with the same name. section 22.2
  • Nested functions add another scope: an inner function can use names available in its enclosing function, while the global scope contains only the outer definition. section 22.3

How Get Programming: Learn to code with Python covers it

How deep it goes
Works through scope rules, access, shadowing, failed assignment, nested functions, and an execution trace.
Examples
Uses same-named `peter` variables, readable scope listings, failed modification, nested functions, and an odd-or-even trace.
What you can do after
Diagnose variable-resolution results and explain why function reads, local shadowing, or assignments succeed or fail.
How it connects
Connects global variables with scope, local variables, functions, parameters, and nested functions.

Also explained in

Compare how 12 books explain global variable →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Get Programming: Learn to code with Python. The section links point to the parts of the book it draws on.