Python – Scope of Variables

The scope of a variable determines the portion of program where you can access a particular identifier.

Python has two scope of variables: global and local.

Global Variables

The variables which are not declared in the function (outside the function) and can be used anywhere in the program. Global variables are defined the file layer. They are assigned as soon as the file is run for the first time.

for example:

a = 30
def number():
    b = 20
    print(b)

print(a)
number()

#OUTPUT
30
20

In the above example, a is present everywhere in your code. So ‘a’ can be used even by this function and turn it to the global, because it is outside the function. But if you also use ‘b’ outside the function, it will throw an error.

Local variables

The variables which are declared within any function can be used within that function only.

for example:

a = 30
def number():
    b = 20
    print(b)

print(a)
number()

#OUTPUT
30
20

In the above example, the local variable ‘b’ is present inside the function, which can be used only within the given function.

Let take another example:

a = 30
def add(b):
    c = 30
    print("c = ", c)
    sum = b + c
    print("Addition is: ", sum)

print(a)
add(40)
print(c)

#OUTPUT
30
c = 30
Addition is: 70
Traceback (most recent call last):
  File "scope_of_variable.py", line 19, in <module>
    print(c)
NameError: name 'c' is not defined

Here if you try to print ‘c’, which is inside add() function, it is not available outside the function because, it is not a global variable, it is a local variable. So everything which is within add() function is local to add().

Wordpress Social Share Plugin powered by Ultimatelysocial
Wordpress Social Share Plugin powered by Ultimatelysocial