🚀 LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
🎓 COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.
REFERENCEpython

python Documentation

LOADING ENGINE...

Scope (Global / Local)

AI & DATA SCIENCE // scope-global-local

Scope determines where in your code a variable name is visible: local scope is confined to the function it's created in, while global scope spans the entire module.

Syntax

x = 1  # global

def func():
    y = 2  # local
    global x
    x = 3

Deep Dive Course

Every variable assigned inside a function is local to that function by default, existing only for the duration of that call and invisible outside it — this is why two different functions can each use a variable with the same name without conflicting. A function can read a global variable without any special syntax, but assigning to a name inside a function makes Python treat it as local for the entire function body, unless you explicitly declare it with the global keyword first, telling Python to modify the module-level variable instead of creating a new local one.

1Understanding Scope (Global / Local)

Every variable assigned inside a function is local to that function by default, existing only for the duration of that call and invisible outside it — this is why two different functions can each use a variable with the same name without conflicting. A function can read a global variable without any special syntax, but assigning to a name inside a function makes Python treat it as local for the entire function body, unless you explicitly declare it with the global keyword first, telling Python to modify the module-level variable instead of creating a new local one.

💡

Needing the global keyword inside a function is often a sign that the logic would be cleaner as a value passed in and returned out, rather than a function silently mutating shared state — reach for it deliberately, not as a first resort.

editor.html
counter = 0

def increment():
    global counter
    counter += 1

increment()
increment()
print(counter)
localhost:3000

2Practical Example

Here is a real-world application of Scope (Global / Local) showing how it is used in production Python code.

editor.html
def make_local():
    message = "I'm local"
    print(message)

make_local()
print("message" in dir())
localhost:3000

3Best Practices

Follow these guidelines when working with Scope (Global / Local):

1. Prefer passing values in as parameters and returning results out, over mutating global variables from inside functions

2. Use the global keyword explicitly and sparingly, only when a function genuinely needs to modify module-level state

3. Avoid shadowing a global name with a same-named local variable unintentionally — it's a common source of confusing bugs, especially in longer functions

⚠️

Tip: Needing the global keyword inside a function is often a sign that the logic would be cleaner as a value passed in and returned out, rather than a function silently mutating shared state — reach for it deliberately, not as a first resort.

editor.html
counter = 0

def increment():
    global counter
    counter += 1

increment()
increment()
print(counter)
localhost:3000

Examples

Example 01Basic Usage
counter = 0

def increment():
    global counter
    counter += 1

increment()
increment()
print(counter)
Example 02Advanced Example
def make_local():
    message = "I'm local"
    print(message)

make_local()
print("message" in dir())

Best Practices

  • Prefer passing values in as parameters and returning results out, over mutating global variables from inside functions
  • Use the global keyword explicitly and sparingly, only when a function genuinely needs to modify module-level state
  • Avoid shadowing a global name with a same-named local variable unintentionally — it's a common source of confusing bugs, especially in longer functions

Interview Question

Why does assigning to a variable inside a function make Python treat it as local for the whole function, even on lines before the assignment?

Hint: Think about how Python decides scope — at compile time or at each individual line?

Python determines whether a name is local or global for an entire function body at compile time, by scanning the whole function for assignments to that name, not line by line as the code runs. If there's an assignment to a name anywhere in the function, that name is treated as local throughout the function, even on lines that appear before the assignment — so trying to read it before the assignment raises an UnboundLocalError instead of falling back to a same-named global variable.

Exercises

MediumPractice using Scope (Global / Local) in a real scenario.
View Solution
counter = 0

def increment():
    global counter
    counter += 1

increment()
increment()
print(counter)

Frequently Asked Questions

Why does assigning to a variable inside a function make Python treat it as local for the whole function, even on lines before the assignment?

Python determines whether a name is local or global for an entire function body at compile time, by scanning the whole function for assignments to that name, not line by line as the code runs. If there's an assignment to a name anywhere in the function, that name is treated as local throughout the function, even on lines that appear before the assignment — so trying to read it before the assignment raises an UnboundLocalError instead of falling back to a same-named global variable.

Related Functions

def-keywordarguments-argsnonetype