1.
What is the output of the code shown below?
x=100
def f1():
global x
x=90
def f2():
global x
x=80
print(x)
a) 100
b) 90
c) 80
d) Error
Answer: a
EXPLANATION: The output of the code shown above is 100. This is because the variable ‘x’ has been declared as global and functions f1 and f2 are not called.
2.
Read the code shown below carefully and point out the global variables:
y, z = 1, 2
def f():
global x
x = y+z
a) x
b) y and z
c) x, y and z
d) Neither x, nor y, nor z
Answer: c
EXPLANATION: In the code shown above, x, y and z are global variables inside the function f. y and z are global because they are not assigned in the function. x is a global variable because it is explicitly specified so in the code. Hence, x, y and z are global variables.
3.
What is the output of the code shown below?
x=1
def cg():
global x
x=x+1
cg()
a) 2
b) 1
c) 0
d) Error
Answer: a
EXPLANATION: Since ‘x’ has been declared a global variable, it can be modified very easily within the function. Hence the output is 2.
4.
On assigning a value to a variable inside a function, it automatically becomes a global variable. State whether true or false.
a) True
b) False
Answer: b
EXPLANATION: On assigning a value to a variable inside a function, t automatically becomes a local variable. Hence the above statement is false.
5.
Which is the most appropriate definition for recursion?
a)A function that calls itself
b)A function execution instance that calls another execution instance of the same function
c)A class method that calls another class method
d)An in-built method that is automatically called
Answer: b
EXPLANATION: The appropriate definition for a recursive function is a function execution instance that calls another execution instance of the same function either directly or indirectly.