Q. Following code intends to add a given value to global variable a. What will the following code produce ?
def increase(x): #1
a = a + x #2
return #3
#4
a = 20 #5
b = 5 #6
increase(b) #7
print(a) #8
Answer :-
The above code will produce an error.
The reason being whenever we assign something to a variable inside a function, the variable is created as a local variable. Assignment creates a variable in Python.
Thus in line 2, when variable a is incremented with the passed value x, Python tries to create a local variable a by assigning to it the value of the expression on the right-hand side of the assignment. But variable a also appears on the right-hand side of the assignment, which results in an error because a is undeclared so far in function.
To assign some value to a global variable from within a function, without creating a local variable with the same name, the global statement can be used. So, if we add
global a
In the first line of the function body, the above error will be corrected. Python won't create a local variable a, rather will work with global variable a.
Post a Comment
You can help us by Clicking on ads. ^_^
Please do not send spam comment : )