MyInternships.in

Python Functions

Python Variable Scope

Scope determines where in your code a variable can be seen and used. Python looks variables up using a clear order called the LEGB rule, and understanding it prevents a lot of confusing bugs.


Local Scope

A variable created inside a function is local to that function — it exists only while the function runs and is not visible outside it. Each function call gets its own fresh set of local variables.

Local variables
Python
def greet():
    message = "Hello!"   # local to greet()
    print(message)

greet()
print(message)   # NameError: message is not defined here

Global Scope

A variable created outside of any function, at the top level of your script, is global — it can be read from anywhere, including inside functions, without any special keyword.

Reading a global variable
Python
site_name = "MyInternships"   # global

def show_name():
    print(site_name)   # can read the global directly

show_name()

The global Keyword

Reading a global variable inside a function works automatically, but modifying it requires the global keyword — otherwise Python assumes you are creating a brand new local variable with the same name.

Modifying a global variable
Python
counter = 0

def increment():
    global counter
    counter += 1

increment()
increment()
print(counter)   # 2
⚠️

Overusing global variables makes code harder to test and debug. Prefer passing values in as parameters and returning results instead, wherever practical.

The nonlocal Keyword

nonlocal is used inside a nested function to modify a variable that belongs to its enclosing (outer) function, without making it fully global. It is the key building block behind closures.

nonlocal example
Python
def outer():
    count = 0
    def inner():
        nonlocal count
        count += 1
        return count
    print(inner())   # 1
    print(inner())   # 2

outer()

The LEGB Rule

When Python looks up a name, it searches four scopes in this exact order and stops at the first match: Local, Enclosing, Global, Built-in.

LetterScopeMeaning
LLocalInside the current function
EEnclosingInside any outer (enclosing) function, for nested functions
GGlobalTop level of the module/script
BBuilt-inPython's built-in names, like print or len

Related Python Topics

Keep learning with these closely related lessons.

Ready to use your Python skills?

Find Python, data science and software internships and fresher jobs across India.

Browse Python Internships