local and Global scope of variables

'''
Scope of a variable is defined as the area with in which the variable is accessible.

variable is a label for a location in the memory.

Not all variables are accessible, and not all variables exist for the same amount of time.

types of variables:

variables can be local and global

local variables are the variables that can be accessed in a local scope .ie with in the respective loop/function/if-else statement etc

global variables are the variables that can be accessed in globally

for example
'''
a= 25
def akansha():
a= 10
print("case 1 " , a)
akansha()

''' in the above case 10 is printed as it takes local value of a
'''

a= 25
def akansha():

print("case 2" ,a)
akansha()

''' in the above case 25 is printed as the program could not find a in local scope '''


'''Global key word helps the programmer to get the permission for python to change the global variable
in the local scope'''


a= 25
def akansha():
global a
a =a*2
print("case 3" ,a)
akansha()

'''
In the above example the value of a is changed using the Global key word
'''


'''Nested functions and their scope .'''



def func1():
a = 25 # this is local scope of functon 1
print("This is function 1" ,a)
def func2():
global a # this is local scope of function 2
a=37
# print("this is function 2", a)
func2()
print("This is function 1 after call of function 2" ,a)

func1()
'''
1.a is a local variable of function 1
2.function 2 is trying to change the global variable a (which is not the same as a of function 1)
3.result of before and after function one stays the same as 25 .
4.since global key word does not changes , value of other local variables.
'''


#OUTPUT
'''

case 1 10
case 2 25
case 3 50
This is function 1 25
This is function 1 after call of function 2 25

you can copy the code to your python interpreter and it will work.
'''

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

CheerpJ 1.2 released

How to retrieve and deploy profiles in lightning platform ?

ZkPad roadmap

[Codility] Lesson-02–1: CyclicRotation

7 Chrome extensions to help you boost GitHub activity

My Journey with Udacity and Grow With Google: from Translation to Coding

OpenMetadata 0.8.0 Release

How A Forex API Can Affect Your Finances?

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Akansha Srivastava

Akansha Srivastava

More from Medium

Assert Function in Python

Decorators in Python

HackerRank flippingMatrix Challenge in Python

Catastrophic Forgetting In Machine Learning

Catastrophic forgetting article