Working with Python – Scope of Variable

Introduction

It is important to understand the scope of variable in python. In this Blog post, we are going to discuss about the scope of variable.

Hope it will be interesting.

Local Scope

A variable that is created inside the function is the scope is inside the function. That means we can use this variable within function not the outside of function.

def myfunc():
  x = 
300
  
print(x)

myfunc()

 

Function Inside the Function

The local variable can be accessed from a function within the function

 

def myfunc():
  x = 
300
  
def myinnerfunc():
    
print(x)
  
myinnerfunc()

myfunc()

à300

 

Global Scope

A variable created in the main body of the Python code is a global variable and belongs to the global scope. Global variables are available from within any scope, global and local.

x = 300

def myfunc():
  
print(x)

myfunc()

print(x)

-->300

 

Global Keyword

If you need to create a global variable, but are stuck in the local scope, you can use the global keyword. The global keyword makes the variable global.

 

x = 300

def myfunc():
  
global x
  
x = 200

myfunc()

print(x)

à200

 


 

Hope you like it.

Comments

Popular Posts

Triggering Pipeline in ADF

Working with Python -- File Handling