Python Variable Scope And Lifetime

In this tutorial, we will learn the scope and Lifetime variables in Python. The scope is nothing but the visibility of variables and Lifetime is nothing but the duration which variable is exist

Local Variables inside a function in Python

  • In the local variable, we will declare the variable inside the function.
  • Here funt is the function name.
  • ‘x’ is the variable.

For example

def funt()://it is function    
    x='hello local variable'//variable inside function    
    print(x) 
funt()//here it is function call
output
hello local variable

Variable in function parameter in Python

  • In the parameterizing variable,  we passed the variable inside the function.
  • We will pass the message inside the function declaration. That message we will get as output.

For example

def funt(x)://here 'x' is parameter for this function    
    print(x) 
funt("hello parameter variable")//message passed inside function declearation

 

output
hello parameter variable

global variable in Python

  • In the global variable in the main body, the variable will be defined.
  • It can access any part of the program
  • the variable declared outside the function.

For example

x="welcome to global variable" 
def funt():    
    print(x)//it is calling inside the function 
funt()

 

print(x) //it is calling outside the function
output
welcome to global variable
welcome to global variable

Nested function variable scope in Python

  • A function defined inside another function called nested function.
  • It follows the LIFO structure.

For example.

x="first global"
def funt():
    x="secocnd global"
    print(x)
funt()
print(x)

 

output
secocnd global
first global
  • In the above output, we can observe the LIFO in the function.

Two messages passed inside the function in two same name variables that variable message shows as output.

Also read:

Leave a Reply

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