Difference between local and global variables in Python

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

Global variables have a global scope you 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 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

  • Local variable is declared inside a function whereas 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 are stored on 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 and suggestions on this Python variables 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.