Automation Crunch 😎
January 20, 2022

Variables in Python

Posted on January 20, 2022  •  3 minutes  • 453 words

This article offers the easy understanding of Python variables, valid variable names and difference between local variables & global variables.

Python Variables

A variable in Python is a memory place where a value can be stored. According to the requirements, the value you’ve saved may change in the future.

Rules for assigning names to Python variables

Legal variable names :

Illegal variable names :

Local Variables vs Global variables

Local variables are those which are defined inside a function and its scope is limited to that function only. In other words, we can say that local variables are accessible only inside the function in which it was initialized.

Local Scope : A variable created inside a function belongs to the local scope of that function, and can only be used inside that function.

For example :

# Creating local variables
# Example  (1)
>>> def fun():
...     st = "I Love Python"  # local variable
...     print("Inside function",st)
...
>>> fun() # calling function
Inside function I Love Python  # output

# Example  (2) 
# If we will try to use this local variable outside the function then let’s see what will happen.

>>> def fun():
...     st = "I Love Python"  # local variable
...     print("Inside function",st)
...
>>> fun() # calling function
Inside function I Love Python  # output

>>> print("Outside function:",st) # try to print outside function
NameError: name 'st' is not defined

Global Scope : A variable created in the main body of the Python code is a global variable and belongs to the global scope.

For example :

>>> def fun():    
...     print("Inside function",st)
>>> st = "I Love Python"  # local variable

>>> fun() # calling function
Inside function I Love Python  # output

>>> print("Outside function:",st) # try to print variable outside function
Outside function I Love Python

Note : The variable ‘st’ is defined as the global variable and is used both inside the function as well as outside the function. As there are no locals, the value from the globals will be used.

Follow me

You can find me on