250+ TOP MCQs on Python Global vs Local Variables and Answers

Python Multiple Choice Questions on “Global vs Local Variables – 2”.

1. Which of the following data structures is returned by the functions globals() and locals()?
a) list
b) set
c) dictionary
d) tuple
Answer: c
Clarification: Both the functions, that is, globals() and locals() return value of the data structure dictionary.

2. What will be the output of the following Python code?

x=1
def cg():
	global x
	x=x+1	
cg()
x

a) 2
b) 1
c) 0
d) Error
Answer: a
Clarification: Since ‘x’ has been declared a global variable, it can be modified very easily within the function. Hence the output is 2.

3. On assigning a value to a variable inside a function, it automatically becomes a global variable.
a) True
b) False
Answer: b
Clarification: On assigning a value to a variable inside a function, t automatically becomes a local variable. Hence the above statement is false.

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
Answer: c
Clarification: 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.

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
Answer: d
Clarification: 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.

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
Answer: b
Clarification: 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.

7. What will be the output of the following Python code?

a) Error
b) 4
c) Junk value
d) 1
Answer: d
Clarification: 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.

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()

View Answer

Answer: c
Clarification: The function globals() returns a dictionary of the module namespace, whereas the function locals() returns a dictionary of the current namespace.

 
 

Leave a Reply

Your email address will not be published. Required fields are marked *