Advertisements
Advertisements
Question
Observe the following program carefully, and identify the error:
mynum = 9
def add9():
mynum = mynum + 9
print mynum
add9() #function callShort/Brief Note
Advertisements
Solution
There are two errors in the given program.
- In line 1, ‘mynum’ variable is defined which is a global variable. However, in line 3, a variable with the same name is defined again. Therefore, 'mynum' is treated as a new local variable. As no value has been assigned to it before the operation, hence, it will give an error. The local variable can either be changed to a different name or a value should be assigned to the local 'mynum' variable before line 3.
- The syntax of the ‘print’ function is incorrect. The correct syntax will be ‘print(mynum)’.
shaalaa.com
Scope of a Variable in Python
Is there an error in this question or solution?
