Q. What do you understand by local and global scope of variables? How can you access a global variable inside the function, if function has a variable with same name?


Answer :-

Global scope :-
A global variable is a variable defined in the ‘main’ program (__main__ section). Such variables are said to have global scope.

We can acess or change value global variable by using keyword global.

A variable declared outside of the function or in global scope is known as global variable. This means that global variable can be accessed inside or outside of the function whereas local variable can be used only inside of the function. We can access by declaring variable as global A.

For example : -

def s():
    t = 15
    print (t)
t = 95 # t is Global variable
print (t)
s()
print (t)

Output :-

95
15 
# Here t is in function ( Local variable)
95  # Here t is outside from function ( Global variable)
>>> 

So, here we can clearly see that value of  't' is not changing.

So, if we want to change value of  't' then we have to use global keyword.

Ex:-

def s():
    global t
    t = 15
    print (t)
t = 95
print (t)
s()
print (t)

Output :-

95
15
# t is in function
15 # value of t changed
>>> 


18 Comments

You can help us by Clicking on ads. ^_^
Please do not send spam comment : )

Post a Comment

You can help us by Clicking on ads. ^_^
Please do not send spam comment : )

Previous Post Next Post