Skip to content

Difference between local and global variables in Python

  • by

Python Global variables are variables declared outside of a function and Local variables are declared inside a function.

Global variables have a global scope that can be accessed throughout an entire program, including within functions. And Local variables have a local scope it can be accessed only within the function in which they are declared.

Example difference between local and global variables in Python

Simple example code where name is a local variable, local to the function subdomain(). The web is a global variable accessible anywhere in the module.

Local variables are temporary variables used in a single function definition.

web = "EyeHunts Global"  # global variable


def subdoamin():
    name = "Tutorial Local"  # local variable
    print(name)


subdoamin()

print(web)

Output:

Difference between local and global variables in Python

Using Global and Local Variables

Python program to use the same variable name for both a local and a global variable. Where the local variable will be read in the local scope, and the global variable will be read in the global scope.

Let’s see it by example code.

score = 10


def my_score():
    score = 50
    print("Final Score:", score)


my_score()
print("Initial Score:", score)

Output:

Final Score: 50
Initial Score: 10

Other Difference

  • A local variable is declared inside a function whereas a Global variable is declared outside the function.
  • Local variables are created when the function has started execution and is lost when the function terminates where, Global variable is created as execution starts and is lost when the program ends.
  • Local variables are stored on the stack whereas the Global variable is stored in a fixed location decided by the compiler.
  • Parameters passing is required for local variables whereas it is not necessary for a global variable

Do comment if you have any doubts or suggestions on this Python variables 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 *