Python Programming – Global And Local Variables

You can learn about Functions in Python Programs with Outputs helped you to understand the language better.

Python Programming – Global And Local Variables

A variable’s lifetime is the period of time for which it resides in the memory. The lifetime of variables inside a function is as long as the function executes. They are destroyed once you return from the function. Hence, a function does not remember the value of a variable from its previous calls.
All variables in a program may not be accessible at all locations in that program. This depends on where you have declared a variable. The variable declared in one part of the program may not be accessible to the other parts. The scope of a variable determines the portion of the program where you can access a particular identifier. There are two basic scopes of variables in Python.

  1. Global scope
  2. Local scope

Variables that are defined inside a function body have a local scope. In other words, it is local to that function and those defined outside have a global scope. This means that local variables can be accessed only inside the function in which they are declared, If you then try to access the variable x outside the function, it will give NameError.

Global variables can be accessed throughout the program body by all functions. When you call a function, the variables declared inside it are brought into scope,
def fund ( ) :
x=9 # Local scope
fund ( )
y=9 # Global scope
def func2( ):
func2( )
Let us discuss global scope of a variable in

  1. The global names are variables assigned at the top level of the enclosing module file. It means that it is visible everywhere within the program.
  2. The global names must be declared only if they are assigned within a function.
  3. Global variables must be referenced within a function without being declared. See Example 14.

Demo of local and global variables.

total = 0; # This is global variable.
# Function definition def sum( arg1, arg2 ):
# Add both the parameters and return them.
total = arg1 + arg2; # Here total Is local variable
print(“Inside the function local total : “, total)
return total
# Now you can call sum function
sum( 20, 40 )
print(“Outside the function global total : “, total)

When the above code is executed, it produces the following result:
Inside the function local total: 60
Outside the function global total: 0

global Statements

The global statements are remotely like declaration statements in Python. They do not type or size declarations, though they are namespace declarations. The global statement tells Python that a function plans to change one or more global names, i.e., names that live in the enclosing module’s scope (namespace).

  • A namespace is a practical approach to define the scope, and it helps to avoid name conflicts.


Leave a Reply

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