Skip to content

A local variable in Python | Example code

  • by

A variable declared inside the function is called a local variable in Python. Local variables are accessible only inside the function.

Example local variable in Python

Simple example code creates a local variable inside a function and tries to access it outside those functions.

def foo():
    local_var = "local"


foo()

print(local_var)

Output: shows an error (NameError) because we are trying to access a local variable

A local variable in Python

Example access local variable within a function

def foo():
    local_var = "local"
    print(local_var)


foo()

Output: local

How to use Global and Local variables in the same code

g = "Global "


def foo():
    global g
    l = "Local"
    g = g * 2
    print(g)
    print(l)


foo()

Output:

Global Global
Local

Do comment if you have any doubts or suggestions on this Python variable topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *