A local variable in Python | Example code

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 and suggestions on this Python variable topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

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


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.