Global and local variables

there are two types of variables in python one is local variable and one is global variable in this tutorial we will talk about what actually they are !
a global variable can be reached anywhere in the code but local in just a function where it is created

look at the picture the global variable (x) is reached in every part of the code or code block but the local variable which is (z) can just be used in code block 3 you cannot use it in code block 2 or 1 because its a local but you can use global anywhere
LOCAL VARIABLE
in simple language local variables can only be reached in a single function in which they are created . for more advance local variables can only be reached in their scope I will make a post on scope also defining actually what is that soon .
the example below has two local variables a and b .
def sum(a,b):
sum=a+b
return sum
print(sum(8,6))
the a and b variables which are local variables can only be used in that sum function they actually just exist in the sum function not outside the fuction . local variables will not be executed outside their scope this command will not work !
print(a)
GLOBAL VARIABLE
a global variable can be used in any part of the code because its global in example below we created a global variable x :x=15
def function():
global x
print(x)
function()
print(x)
The global variable x can be used all throughout the program, inside functions or outside.
A global variable can modified inside a function and change for the entire program:
x=15
def function():
global x
z=20
function()
print(x)
After calling function(), the global variable is changed for the entire program.
EXERCISE
Local and global variables can be used together in the same program.
Try to determine the output of this program:
z = 10 def func1():
global z
z = 3
def func2(x,y):
global z
return x+y+z
func1()
total = func2(4,5)
print(total)
thanks for reading -
anonymous
Comments
Post a Comment