Python Multiple Choice Questions & Answers (MCQs) focuses on “Global vs Local Variables – 2”.
Q 1. Which of the following data structures is returned by the functions globals() and locals()?
A. list
B. set
C. dictionary
D. tuple
Show Answer
Answer:-C. dictionaryExplanation
Both the functions, that is, globals() and locals() return value of the data structure dictionary.
Q 2. What will be the output of the following Python code?
x=1
def cg():
global x
x=x+1
cg()
x
A. 0
B. 1
C. 2
D. Error
Show Answer
Answer:-C. 2Explanation
Since ‘x’ has been declared a global variable, it can be modified very easily within the function. Hence the output is 2.
Q 3. On assigning a value to a variable inside a function, it automatically becomes a global variable.
A. True
B. False
Show Answer
Answer:-B. FalseExplanation
On assigning a value to a variable inside a function, t automatically becomes a local variable. Hence the above statement is false.Q 4. What will be the output of the following Python code?
e=”butter”
def f(a): print(a)+e
f(“bitter”)
A. error
B. butter
error
C. bitter
error
D. bitterbutter
Show Answer
Answer:-C. bitter errorExplanation
The output of the code shown above will be ‘bitter’, followed by an error. The error is because the operand ‘+’ is unsupported on the types used above.
Q 5. What happens if a local variable exists with the same name as the global variable you want to access?
A. Error
B. The local variable is shadowed
C. Undefined behavior
D. The global variable is shadowed
Show Answer
Answer:-B. The local variable is shadowedExplanation
If a local variable exists with the same name as the local variable that you want to access, then the global variable is shadowed. That is, preference is given to the local variable.
Q 6. What will be the output of the following Python code?
a=10
globals()[‘a’]=25
print(a)
A. 10
B. 25
C. Junk value
D. Error
Show Answer
Answer:-B. 25Explanation
In the code shown above, the value of ‘a’ can be changed by using globals() function. The dictionary returned is accessed using key of the variable ‘a’ and modified to 25.
Q 7. What will be the output of the following Python code?
def f(): x=4
x=1
f()
x
A. 1
B. 4
C. Junk value
D. Error
Show Answer
Answer:-A. 1Explanation
In the code shown above, when we call the function f, a new namespace is created. The assignment x=4 is performed in the local namespace and does not affect the global namespace. Hence the output is 1.
Q 8. ______________ returns a dictionary of the module namespace.
________________ returns a dictionary of the current namespace.
A. locals()
globals()
B. locals()
locals()
C. globals()
locals()
D. globals()
globals()
Leave a Reply