Python Scope

Local, global and nonlocal variables.

✍️ 3 exercises + code challenge in this lesson

A variable is only available inside the region where it is created: its scope.

  • Local: created inside a function; only usable there.
  • Global: created at the top level; usable everywhere.
  • global x: lets a function change a global variable.
  • nonlocal x: lets a nested function change a variable from the enclosing function.

Key Takeaways: Python Scope

Mastering Python Scope helps you write clean and reliable Python code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

Python Scope Code Example

Python
counter = 0   # global

def increment():
    global counter
    counter += 1

def outer():
    message = "outer"
    def inner():
        nonlocal message
        message = "changed by inner"
    inner()
    return message

increment(); increment()
print("counter:", counter)
print(outer())
Free sign-in required · Google login available

Python Scope Practice Exercises

Check what you learned in “Python Scope”.

/ 3 solved
Fill in the blank

Allow the function to change the global variable.

count = 0
def inc():
     count
    count += 1
✓ Correct! Not quite. Try again.
Multiple choice

A variable created inside a function is…

✓ Correct! Not quite. Try again.
Code challenge

Use the global keyword so calling add() twice makes total 2, then print total.

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services