Shiklo Tools
PDF40
Image20
Calculators & Converters25
Text & Writing13
Developer26
Video14
Audio14
Document14
Data & Spreadsheet12
Web & SEO9
OCR & Scanning5
Archive & File12
Security & Privacy23
Health & Medical29
QR & Barcode5

Python Scope

The scope of a variable is the part of the program where its name can be used. A variable created inside a function is local: it exists only while the function runs and cannot be seen outside it. A variable created at the top level of the file is global: it can be read anywhere in the file. Scope keeps functions independent, so a name used inside one function cannot clash with the same name elsewhere.

Local variables

def make_total():
    total = 10 + 20       # local to make_total
    return total

print(make_total())
total = "something else"  # a different, global variable
print(make_total(), total)
Output
30
30 something else

The total inside the function and the total outside are two different variables that happen to share a name. Each call of the function starts with fresh local variables.

Reading a global variable

A function can read a global variable without doing anything special:

tax_rate = 0.18

def with_tax(price):
    return price * (1 + tax_rate)

print(with_tax(200))
Output
236.0

Changing a global variable

Assigning to a name inside a function creates a local variable, even when a global with the same name exists. So this function fails:

count = 0

def add_one():
    count = count + 1

add_one()
Output
Traceback (most recent call last):
  File "main.py", line 6, in <module>
    add_one()
    ~~~~~~~^^
  File "main.py", line 4, in add_one
    count = count + 1
            ^^^^^
UnboundLocalError: cannot access local variable 'count' where it is not associated with a value

Because the function assigns to count, Python treats count as local throughout the function, and the right-hand side tries to read the local before it has a value. The global keyword says that the name means the global variable:

count = 0

def add_one():
    global count
    count = count + 1

add_one()
add_one()
print(count)
Output
2

nonlocal does the same for a variable of an enclosing function when one function is defined inside another.

A better design

Functions that change globals are hard to follow, because any call may change the program's state. It is usually clearer to pass values in as parameters and give results back with return, as in count = add_one(count). Keep global for small scripts, and for real constants such as TAX_RATE, written in capitals by convention.

Practice exercises

  1. Write a function that creates a local variable, and show that it cannot be printed outside the function.
  2. Read a global constant inside a function to convert kilometres to miles.
  3. Rewrite the counter above without global, passing the count in and returning the new count.
  4. Explain why the UnboundLocalError example fails, in your own words.