Python Question and Answers – Built-in Functions – 1
This set of Python Multiple Choice Questions & Answers (MCQs)
focuses on “Built-in Functions – 1”.
1. Which of the following functions is a built-in function in any([2>8, 4>2, 1>2])
python? a) Error b) True c) False d) 4>2
a) seed() b) sqrt() c) factorial() d) print() 7. What is the output of the function shown below?
2. What is the output of the expression: import math
round(4.576) abs(math.sqrt(25))
a) 4.5 b) 5 c) 4 d) 4.6 a) Error b) -5 c) 5 d) 5.0
3. The function pow(x,y,z) is evaluated as: 8. What are the outcomes of the functions shown below?
a) (x**y)**z b) (x**y) / z sum(2,4,6)
c) (x**y) % z d) (x**y)*z sum([1,2,3])
4. What is the output of the function shown below? a) Error, 6 b) 12, Error c) 12, 6 d) Error, Error
all([2,4,0,6]) 9. What is the output of the function:
a) Error b) True c) False c) 0 all(3,0,4.2)
5. What is the output of the expression? a) True b) False c) Error d) 0
round(4.5676,2)? 10. What is the output of the functions shown below?
a) 4.5 b) 4.6 c) 4.57 d) 4.56 min(max(False,-3,-4), 2,7)
6. What is the output of the following function? a) 2 b) False c) -3 d) -4
Python Question and Answers – Built-in Functions – 2
This set of Python Multiple Choice Questions & Answers (MCQs)
focuses on “Built-in Functions – 2”.
1. What are the outcomes of the following functions? 6. The function complex(‘2-3j’) is valid but the function
chr(‘97’) complex(‘2 – 3j’) is invalid. State whether this statement is
chr(97) true or false.
a) a and Erro b) ‘a’ c) Error d) Error a) True b) False
Error
2. What is the output of the following function? 7. What is the output of the function shown below?
complex(1+2j) list(enumerate([2, 3]))
a) Error b) 1 c) 2j d) 1+2j a) Error b) [(1, 2), (2, 3)]
3. What is the output of the function complex() ? c) [(0, 2), (1, 3)] d) [(2, 3)]
a) 0j b) 0+0j c) 0 d) Error 8. What are the outcomes of the function shown below?
4. The function divmod(a,b), where both ‘a’ and ‘b’ are x=3
integers is evaluated as: eval('x^2')
a) (a%b, a//b) b) (a//b, a%b) a) Error b) 1 c) 9 d) 6
c) (a//b, a*b) c) (a/b, a%b) 9. What is the output of the functions shown below?
5. What is the output of the functions shown below? float('1e-003')
divmod(10.5,5) float('2e+003')
divmod(2.4,1.2) a) 3.00 and 300 b) 0.001 and 2000.0
a) (2.00, 0.50) and (2.00, 0.00) b) (2, 0.5) and (2, 0) c) 0.001 and 200 d) Error and 2003
c) (2.0, 0.5) and (2.0, 0.0) d) (2, 0.5) and (2) 10. Which of the following functions does not necessarily
accept only iterables as arguments?
a) enumerate() b) all() c) chr() d) max()
Python Question and Answers – Built-in Functions – 3
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Built-in
Functions – 3”.
1. Which of the following functions accepts only integers as a) reverse(l) b) list(reverse[(l)])
arguments? c) reversed(l) d) list(reversed(l))
a) ord() b) min() c) chr() d) any() 3. The output of the function:
2. Suppose there is a list such that: l=[2,3,4]. float(' -12345\n')
If we want to print this list in reverse order, which of the (Note that the number of blank spaces before the number is
following methods should be used? 5)
a) -12345.0 (5 blank spaces before the number) a) min() b) divmod() c) all() d) float()
b) -12345.0
c) Error 7. What is the output of the function shown below?
d) -12345.000000000…. (infinite decimal places) hex(15)
4. What is the output of the functions shown below? a) f b) 0xF c) 0Xf d) 0xf
ord(65) 8. Which of the following functions does not throw an error?
ord(‘A’) a) ord() b) ord(‘ ‘) c) ord(”) d) ord(“”)
a) A and 65 b) Error and 65 9. What is the output of the function:
c) A and Error c) Error and Error len(["hello",2, 4, 6])
5. What is the output of the functions shown below? a) 4 b) 3 c) Error d) 6
float(‘-infinity’) 10. What is the output of the function shown below?
float(‘inf’) oct(7)
a) –inf and inf b) –infinity and inf oct(‘7’)
c) Error and Error d) Error and Junk value a) Error and 07 b) 0o7 and Error
6. Which of the following functions will not result in an c) 0o7 and Error d) 07 and 0o7
error when no arguments are passed to it?
Python MCQ of – Function – 1
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Function – 1”.
1. Which of the following is the use of function in python? print(b, 'is maximum')
a) Functions are reusable pieces of programs printMax(3, 4)
b) Functions don’t provide better modularity for your a) 3 b) 4 c) 4 is maximum d) None of the mentioned
application 5. What is the output of the below program ?
c) you can’t also create your own functions x = 50
d) All of the mentioned def func(x):
2. Which keyword is use for function? print('x is', x)
a) Fun b) Define c) Def d) Function x=2
3. What is the output of the below program? print('Changed local x to', x)
def sayHello(): func(x)
print('Hello World!') print('x is now', x)
sayHello() a) x is now 50 b) x is now 2
sayHello() c) x is now 100 d) None of the mentioned
a) Hello World! and Hello World! 6. What is the output of the below program?
b) ‘Hello World!’ and ‘Hello World!’ x = 50
c) Hello and Hello def func():
d) None of the mentioned global x
Answer: a print('x is', x)
EXPLANATION: Functions are defined using the def x=2
keyword. After this keyword comes an identifier name for print('Changed global x to', x)
the function, followed by a pair of parentheses which may func()
enclose some names of variables, and by the final colon that print('Value of x is', x)
ends the line. Next follows the block of statements that are a) x is 50
part of this function. Changed global x to 2
def sayHello(): Value of x is 50
print('Hello World!') # block belonging to the function b) x is 50
# End of function # Changed global x to 2
sayHello() # call the function Value of x is 2
sayHello() # call the function again c) x is 50
4. What is the output of the below program? Changed global x to 50
def printMax(a, b): Value of x is 50
if a > b: d) None of the mentioned
print(a, 'is maximum') Answer: b
elif a == b: EXPLANATION: The global statement is used to declare that
print(a, 'is equal to', b) x is a global variable – hence, when we assign a value to x
else:
inside the function, that change is reflected when we use the you can give values for such parameters by naming them –
value of x in the main block. this is called keyword arguments – we use the name
7. What is the output of below program? (keyword) instead of the position (which we have been using
def say(message, times = 1): all along) to specify the arguments to the function.
print(message * times) The function named func has one parameter without a
say('Hello') default argument value, followed by two parameters with
say('World', 5) default argument values.
a) Hello and WorldWorldWorldWorldWorld In the first usage, func(3, 7), the parameter a gets the value
b) Hello and World 5 3, the parameter b gets the value 7 and c gets the default
c) Hello and World,World,World,World,World value of 10.
d) Hello and HelloHelloHelloHelloHello In the second usage func(25, c=24), the variable a gets the
Answer: a value of 25 due to the position of the argument. Then, the
EXPLANATION: For some functions, you may want to make parameter c gets the value of 24 due to naming i.e. keyword
some parameters optional and use default values in case the arguments. The variable b gets the default value of 5.
user does not want to provide values for them. This is done In the third usage func(c=50, a=100), we use keyword
with the help of default argument values. You can specify arguments for all specified values. Notice that we are
default argument values for parameters by appending to the specifying the value for parameter c before that for a even
parameter name in the function definition the assignment though a is defined before c in the function definition.
operator (=) followed by the default value. 9. What is the output of below program?
The function named say is used to print a string as many def maximum(x, y):
times as specified. If we don’t supply a value, then by if x > y:
default, the string is printed just once. We achieve this by return x
specifying a default argument value of 1 to the parameter elif x == y:
times. return 'The numbers are equal'
In the first usage of say, we supply only the string and it else:
prints the string once. In the second usage of say, we supply return y
both the string and an argument 5 stating that we want to say print(maximum(2, 3))
the string message 5 times. a) 2 b) 3 c) The numbers are equal
d) None of the mentioned
8. What is the output of the below program? Answer: b
def func(a, b=5, c=10): EXPLANATION: The maximum function returns the
print('a is', a, 'and b is', b, 'and c is', c) maximum of the parameters, in this case the numbers
func(3, 7) supplied to the function. It uses a simple if..else statement to
func(25, c = 24) find the greater value and then returns that value.
func(c = 50, a = 100) 10. Which of the following is a features of DocString?
a) a is 7 and b is 3 and c is 10 a) Provide a convenient way of associating documentation
a is 25 and b is 5 and c is 24 with Python modules, functions, classes, and methods
a is 5 and b is 100 and c is 50 b) All functions should have a docstring
b) a is 3 and b is 7 and c is 10 c) Docstrings can be accessed by the __doc__ attribute on
a is 5 and b is 25 and c is 24 objects
a is 50 and b is 100 and c is 5 d) All of the mentioned
c) a is 3 and b is 7 and c is 10 Answer: d
a is 25 and b is 5 and c is 24 EXPLANATION: Python has a nifty feature called
a is 100 and b is 5 and c is 50 documentation strings, usually referred to by its shorter
d) None of the mentioned name docstrings. DocStrings are an important tool that you
Answer: c should make use of since it helps to document the program
EXPLANATION: If you have some functions with many better and makes it easier to understand.
parameters and you want to specify only some of them, then
Python MCQ of – Function – 2
This set of Python Questions for entrance examinations focuses on “Functions”.
1. Which are the advantages of functions in python? c) Improving clarity of the code
a) Reducing duplication of code d) All of the mentioned
b) Decomposing complex problems into simpler pieces Answer: d
EXPLANATION: None. is used to return values from a function. A function may or
2. What are the two main types of functions? may not return a value. If a function does not have a return
a) Custom function keyword, it will send a none value.
b) Built-in function & User defined function 8. What is the output of the below program?
c) User function def C2F(c):
d) System function return c * 9/5 + 32
Answer: b print C2F(100)
EXPLANATION: Built-in functions and user defined ones. print C2F(0)
The built-in functions are part of the Python language. a) 212 and 32 b) 314 and 24
Examples are: dir(), len() or abs(). The user defined c) 567 and 98 d) None of the mentioned
functions are functions created with the def keyword. Answer: a
3. Where is function defined? EXPLANATION: The code shown above is used to convert a
a) Module b) Class temperature in degree celsius to fahrenheit.
c) Another function d) All of the mentioned 9. What is the output of the below program?
Answer: d def power(x, y=2):
EXPLANATION: Functions can be defined inside a module, r=1
a class or another function. for i in range(y):
4. What is called when a function is defined inside a class? r=r*x
a) Module b) Class return r
c) Another function d) Method print power(3)
Answer: d print power(3, 3)
a) 212 and 32 b) 9 and 27
EXPLANATION: None.
c) 567 and 98 d) None of the mentioned
5. Which of the following is the use of id() function in
python?
Answer: b
a) Id returns the identity of the object EXPLANATION: The arguments in Python functions may
b) Every object doesn’t have a unique id have implicit values. An implicit value is used, if no value is
c) All of the mentioned provided. Here we created a power function. The function
d) None of the mentioned has one argument with an implicit value. We can call the
Answer: a function with one or two arguments.
10. What is the output of the below program?
EXPLANATION: Each object in Python has a unique id. The
def sum(*args):
id() function returns the object’s id.
'''Function returns the sum
6. Which of the following refers to mathematical function?
of all values'''
a) sqrt b) rhombus c) add d) rhombus
r=0
Answer: a
for i in args:
EXPLANATION: Functions that are always available for r += i
usage, functions that are contained within external modules, return r
which must be imported and functions defined by a print sum.__doc__
programmer with the def keyword. print sum(1, 2, 3)
Eg: math import sqrt print sum(1, 2, 3, 4, 5)
A sqrt() function is imported from the math module. a) 6 and 15 b) 6 and 100
7. What is the output of below program? c) 123 and 12345 d) None of the mentioned
def cube(x): Answer: a
return x * x * x
EXPLANATION: We use the * operator to indicate, that the
x = cube(3)
function will accept arbitrary number of arguments. The
print x
sum() function will return the sum of all arguments. The first
a) 9 b) 3 c) 27 d) 30
string in the function body is called the function
Answer: c
documentation string. It is used to document the function.
EXPLANATION: A function is created to do a specific task. The string must be in triple quotes.
Often there is a result from such a task. The return keyword
Python MCQ of – Function – 3
This set of Python Questions for campus interview focuses on “Functions”.
1. Python supports the creation of anonymous functions at 5. Lambda is a statement.
runtime, using a construct called __________ a) True b) False
a) Lambda 6. Lambda contains block of statements
b) pi a) True b) False
c) anonymous Answer: b
d) None of the mentioned EXPLANATION: None.
Answer: a 7. What is the output of below program?
EXPLANATION: Python supports the creation of def f(x, y, z): return x + y + z
anonymous functions (i.e. functions that are not bound to a f(2, 30, 400)
name) at runtime, using a construct called lambda. Lambda a) 432 b) 24000 c) 430 d) No output
functions are restricted to a single expression. They can be Answer: a
used wherever normal functions can be used. EXPLANATION: None.
2. What is the output of this program?
y=6 8. What is the output of below program?
z = lambda x: x * y def writer():
print z(8) title = 'Sir'
a) 48 b) 14 c) 64 d) None of the mentioned name = (lambda x:title + ' ' + x)
Answer: a return name
EXPLANATION: The lambda keyword creates an who = writer()
anonymous function. The x is a parameter, that is passed to who('Arthur')
the lambda function. The parameter is followed by a colon a) Arthur Sir b) Sir Arthur
character. The code next to the colon is the expression that is c) Arthur d) None of the mentioned
executed, when the lambda function is called. The lambda Answer: b
function is assigned to the z variable. EXPLANATION: None.
The lambda function is executed. The number 8 is passed to 9. What is the output of this program?
the anonymous function and it returns 48 as the result. Note L = [lambda x: x ** 2,
that z is not a name for this function. It is only a variable to lambda x: x ** 3,
which the anonymous function was assigned. lambda x: x ** 4]
3. What is the output of below program? for f in L:
lamb = lambda x: x ** 3 print(f(3))
print(lamb(5)) a) 27 and 81 and 343 b) 6 and 12
a) 15 b) 555 c) 125 d) None of the mentioned c) 9 and 27 and 81 d) None of the mentioned
Answer: c Answer: c
EXPLANATION: None. EXPLANATION: None.
4. Does Lambda contains return statements? 10. What is the output of this program?
a) True b) False min = (lambda x, y: x if x < y else y)
Answer: b min(101*99, 102*98)
EXPLANATION: lambda definition does not include a return a) 9997 b) 9999 c) 9996 d) None of the mentioned
statement. it always contains an expression which is Answer: c
returned. Also note that we can put a lambda definition EXPLANATION: None.
anywhere a function is expected. We don’t have to assign it
to a variable at all.
Python MCQ of – Function – 4
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Function –
4”.
1. What is a variable defined outside a function EXPLANATION: The value of a variable defined outside all
referred to as? function definitions is referred to as a global variable and
a)A static variable b)A global variable can be used by multiple functions of the program.
c)A local variable d)An automatic variable 2.What is a variable defined inside a function referred to as?
Answer: b a)A global variable b)A volatile variable
c)A local variable d)An automatic variable
Answer: c
EXPLANATION: The variable inside a function is called as i=i+j
local variable and the variable definition is confined only to j=j+1
that function. print(i, j)
3.What is the output of the following code? change(j = 1, i = 2)
i=0 a)An exception is thrown because of conflicting values
def change(i): b)1 2 c)3 3 d)3 2
i=i+1 Answer: d
return i EXPLANATION: The values given during function call is
change(1) taken into consideration, that is, i=2 and j=1.
print(i) 7.What is the output of the following code?
a)1 def change(one, *two):
b)Nothing is displayed print(type(two))
c)0 change(1,2,3,4)
d)An exception is thrown a)Integer b)Tuple
Answer: c c)Dictionary d)An exception is thrown
EXPLANATION: Any change made in to an immutable data Answer: b
type in a function isn’t reflected outside the function. EXPLANATION: The parameter two is a variable parameter
4. What is the output of the following piece of code? and consists of (2,3,4). Hence the data type is tuple.
def a(b): 8. If a function doesn’t have a return statement, which of the
b = b + [5] following does the function return?
c = [1, 2, 3, 4] a)int b)null c)None
a(c) d)An exception is thrown without the return statement
print(len(c)) Answer: c
a)4 b)5 c)1 d)An exception is thrown EXPLANATION: A function can exist without a return
Answer: b statement and returns None if the function doesn’t have a
EXPLANATION: Since a list is mutable, any change made in return statement.
the list in the function is reflected outside the function. 9. What is the output of the following code?
5.What is the output of the following code? def display(b, n):
a=10 while n > 0:
b=20 print(b,end="")
def change(): n=n-1
global b display('z',3)
a=45 a)zzz b)zz
b=56 c)An exception is executed d)Infinite loop
change() Answer: a
print(a) EXPLANATION: The loop runs three times and ‘z’ is printed
print(b) each time.
a)10 and 56 b)45 and 56 10. What is the output of the following piece of code?
c)10 and 20 d)Syntax Error def find(a, **b):
Answer: a print(type(b))
EXPLANATION: The statement “global b” allows the global find('letters',A='1',B='2')
value of b to be accessed and changed. Whereas the variable a)String b)Tuple
a is local and hence the change isn’t reflected outside the c)Dictionary d)An exception is thrown
function. Answer: c
6. What is the output of the following code? EXPLANATION: b combines the remaining parameters into
def change(i = 1, j = 2): a dictionary.
Python MCQ of – Argument Parsing 1
This set of Python Puzzles focuses on “Argument Parsing”.
1. What is the type of each element in sys.argv? a) number of arguments b) number of arguments + 1
a) set b) list c) tuple d) string c) number of arguments – 1 d) none of the mentioned
Answer: d Answer: b
EXPLANATION: It is a list of strings.
2. What is the length of sys.argv?
EXPLANATION: The first argument is the name of the return total + 1
program itself. Therefore the length of sys.argv is one more total = 0
than the number arguments. print(foo())
3. What is the output of the following code? a) 0 b) 1 c) error d) none of the mentioned
def foo(k): Answer: b
k[0] = 1 EXPLANATION: It is possible to read the value of a global
q = [0] variable directly.
foo(q)
print(q) 8. What is the output of the following code?
a) [0]. ) [1]. c) [1, 0]. d) [0, 1]. def foo():
Answer: b total += 1
EXPLANATION: Lists are passed by reference. return total
4. How are keyword arguments specified in the function total = 0
heading? print(foo())
a) one star followed by a valid identifier a) 0 b) 1 c) error d) none of the mentioned
b) one underscore followed by a valid identifier Answer: c
c) two stars followed by a valid identifier EXPLANATION: It is not possible to change the value of a
d) two underscores followed by a valid identifier global variable without explicitly specifying it.
Answer: c 9. What is the output of the following code?
EXPLANATION: Refer documentation. def foo(x):
5. How many keyword arguments can be passed to a x = ['def', 'abc']
function in a single function call? return id(x)
a) zero b) one c) zero or more d) one or more q = ['abc', 'def']
Answer: c print(id(q) == foo(q))
EXPLANATION: zero keyword arguments may be passed if a) True b) False c) None d) Error
all the arguments have default values. Answer: b
6. What is the output of the following code? EXPLANATION: A new object is created in the function.
def foo(fname, val): 10. What is the output of the following code?
print(fname(val)) def foo(i, x=[]):
foo(max, [1, 2, 3]) x.append(i)
foo(min, [1, 2, 3]) return x
a) 3 1 b) 1 3 c) error d) none of the mentioned for i in range(3):
Answer: a print(foo(i))
EXPLANATION: It is possible to pass function names as a) [0] [1] [2] b) [0] [0, 1] [0, 1, 2].
arguments to other functions. c) [1] [2] [3]. d) [1] [1, 2] [1, 2, 3].
7. What is the output of the following code? Answer: b
def foo(): EXPLANATION: When a list is a default value, the same list
will be reused.
Python MCQ of – Argument Parsing 2
This set of Tricky Python Questions & Answers focuses on “Argument Parsing”.
1. What is the output of the following code? a) one star followed by a valid identifier
def foo(k): b) one underscore followed by a valid identifier
k = [1] c) two stars followed by a valid identifier
q = [0] d) two underscores followed by a valid identifier
foo(q) Answer: a
print(q) EXPLANATION: Refer documentation.
a) [0]. b) [1]. c) [1, 0]. d) [0, 1]. 3. Which module in the python standard library parses
Answer: a options received from the command line?
EXPLANATION: A new list object is created in the function a) getopt b) os c) getarg d) main
and the reference is lost. This can be checked by comparing Answer: a
the id of k before and after k = [1]. EXPLANATION: getopt parses options received from the
2. How are variable length arguments specified in the command line.
function heading? 4. What is the type of sys.argv?
a) set b) list c) tuple d) string 8. What is the output of the following code?
Answer: b def foo(x):
EXPLANATION: It is a list of elements. x[0] = ['def']
5. What is the value stored in sys.argv[0]? x[1] = ['abc']
a) null return id(x)
b) you cannot access it q = ['abc', 'def']
c) the program’s name print(id(q) == foo(q))
d) the first argument a) True b) False c) None d) Error
Answer: c Answer: a
EXPLANATION: Refer documentation. EXPLANATION: The same object is modified in the
6. How are default arguments specified in the function function.
heading? 9. Where are the arguments received from the command line
a) identifier followed by an equal to sign and the default value stored?
b) identifier followed by the default value within backticks (“) a) sys.argv b) os.argv
c) identifier followed by the default value within square c) argv d) none of the mentioned
brackets ([]) Answer: a
d) identifier EXPLANATION: Refer documentation.
Answer: a 10. What is the output of the following?
EXPLANATION: Refer documentation. def foo(i, x=[]):
7. How are required arguments specified in the function x.append(x.append(i))
heading? return x
a) identifier followed by an equal to sign and the default for i in range(3):
value y = foo(i)
b) identifier followed by the default value within backticks print(y)
(“) a) [[[0]], [[[0]], [1]], [[[0]], [[[0]], [1]], [2]]].
c) identifier followed by the default value within square b) [[0], [[0], 1], [[0], [[0], 1], 2]].
brackets ([]) c) [0, None, 1, None, 2, None].
d) identifier d) [[[0]], [[[0]], [1]], [[[0]], [[[0]], [1]], [2]]].
Answer: d Answer: c
EXPLANATION: Refer documentation. EXPLANATION: append() returns None.
Python MCQ of – Global vs Local Variables – 1
This set of Python Multiple Choice Questions & Answers (MCQs)
focuses on “Global vs Local Variables – 1”.
1. The output of the code shown below is: Answer: b
def f1(): EXPLANATION: The variable x is a local variable. It is first
x=15 printed and then modified. Hence the output of this code is
print(x) 100.
x=12 3. What is the output of the code shown below?
f1() def san(x):
a) Error b) 12 c) 15 d) 1512 print(x+1)
Answer: c x=-2
EXPLANATION: In the code shown above, x=15 is a local x=4
variable whereas x=12 is a global variable. Preference is san(12)
given to local variable over global variable. Hence the output a) 13 b) 10 c) 2 d) 5
of the code shown above is 15. Answer: a
2. What is the output of the code shown below? EXPLANATION: The value passed to the function san() is
def f1(): 12. This value is incremented by one and printed. Hence the
x=100 output of the code shown above is 13.
print(x) 4. What is the output of the code shown?
x=+1 def f1():
f1() global x
a) Error b) 100 c) 101 d) 99 x+=1
print(x) world
x=12 hello
print("x") 8. What is the output of the code shown below?
a) Error b) 13 c) 13 d) x def f1(a,b=[]):
Answer: d b.append(a)
EXPLANATION: In the code shown above, the variable ‘x’ return b
is declared as global within the function. Hence the output is print(f1(2,[3,4]))
‘x’. Had the variable ‘x’ been a local variable, the output a) [3,2,4] b) [2,3,4] c) Error d) [3,4,2]
would have been: Answer: d
13 EXPLANATION: In the code shown above, the integer 2 is
5. What is the output of the code shown below? appended to the list [3,4]. Hence the output of the code is
def f1(x): [3,4,2]. Both the variables a and b are local variables.
global x 9. What is the output of the code shown below?
x+=1 def f(p, q, r):
print(x) global s
f1(15) p = 10
print("hello") q = 20
a) error b) hello c) 16 d) 16 r = 30
hello s = 40
Answer: a print(p,q,r,s)
EXPLANATION: The code shown above will result in an p,q,r,s = 1,2,3,4
error because ‘x’ is a global variable. Had it been a local f(5,10,15)
variable, the output would be: 16 a) 1 2 3 4 b) 5 10 15 4
hello c) 10 20 30 40 d) 5 10 15 40
6. What is the output of the following code? Answer: c
x=12 EXPLANATION: The above code shows a combination of
def f1(a,b=x): local and global variables. The output of this code is: 10 20
print(a,b) 30 40
x=15 10. What is the output of the code shown below?
f1(4) def f(x):
a) Error b) 12 4 c) 4 12 d) 4 15 print("outer")
Answer: c def f1(a):
EXPLANATION: At the time of leader processing, the value print("inner")
of ‘x’ is 12. It is not modified later. The value passed to the print(a,x)
function f1 is 4. Hence the output of the code shown above is f(3)
4 12. f1(1)
7. What is the output of the code shown? a) outer and error
def f(): b) inner and error
global a c) outer and inner
print(a) d) error
a = "hello" Answer: a
print(a) EXPLANATION: The error will be caused due to the
a = "world" statement f1(1) because the function is nested. If f1(1) had
f() been called inside the function, the output would have been
print(a) different and there would be no error.
a) hello and hello and world 11. The output of code shown below is:
b) world and world and hello x=5
c) hello and world andworld def f1():
d) world and hello and world global x
Answer: b x=4
EXPLANATION: Since the variable ‘a’ has been explicitly def f2(a,b):
specified as a global variable, the value of a passed to the global x
function is ‘world’. Hence the output of this code is: world return a+b+x
f1()
total = f2(1,2) x = y+z
print(total) a) x b) y and z
a) Error b) 7 c) 8 d) 15 c) x, y and z d) Neither x, nor y, nor z
Answer: b Answer: c
EXPLANATION: In the code shown above, the variable ‘x’ EXPLANATION: In the code shown above, x, y and z are
has been declared as a global variable under both the global variables inside the function f. y and z are global
functions f1 and f2. The value returned is a+b+x = 1+2+4 = because they are not assigned in the function. x is a global
7. variable because it is explicitly specified so in the code.
12. What is the output of the code shown below? Hence, x, y and z are global variables.
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 within the functions f1 and f2.
13. Read the code shown below carefully and point out the
global variables:
y, z = 1, 2
def f():
global x
Python MCQ of – Global vs Local Variables – 2
This set of Python Multiple Choice Questions & Answers (MCQs)
focuses on “Global vs Local Variables – 2”.
1. Which of the following data structures is returned by the EXPLANATION: On assigning a value to a variable inside a
functions globals() and locals()? function, t automatically becomes a local variable. Hence the
a) list b) set c) dictionary d) tuple above statement is false.
Answer: c 4. What is the output of the code shown below?
EXPLANATION: Both the functions, that is, globals() and e="butter"
locals() return value of the data structure dictionary. def f(a): print(a)+e
2. What is the output of the code shown below? f("bitter")
x=1 a) error b) butter error c) bitter
def cg(): error
global x d) bitterbutter
x=x+1 Answer: c
cg() EXPLANATION: The output of the code shown above will
a) 2 b) 1 c) 0 d) Error be ‘bitter’, followed by an error. The error is because the
Answer: a operand ‘+’ is unsupported on the types used above.
EXPLANATION: Since ‘x’ has been declared a global 5. What happens if a local variable exists with the same
variable, it can be modified very easily within the function. name as the global variable you want to access?
Hence the output is 2. a) Error b) The local variable is shadowed
3. On assigning a value to a variable inside a function, it c) Undefined behavior d) The global variable is shadowed
automatically becomes a global variable. State whether true Answer: d
or false. EXPLANATION: If a local variable exists with the same
a) True b) False name as the local variable that you want to access, then the
Answer: b global variable is shadowed. That is, preference is given to
the local variable.
6. What is the output of the code shown below? Answer: d
a=10 EXPLANATION: In the code shown above, when we call the
globals()['a']=25 function f, a new namespace is created. The assignment x=4
print(a) is performed in the local namespace and does not affect the
a) 10 b) 25 c) Junk value d) Error global namespace. Hence the output is 1.
Answer: b 8. ______________ returns a dictionary of the module
EXPLANATION: In the code shown above, the value of ‘a’ namespace.
can be changed by using globals() function. The dictionary ________________ returns a dictionary of the current
returned is accessed using key of the variable ‘a’ and namespace.
modified to 25. a) locals() and globals() b) locals() and locals()
c) globals() and locals() d) globals() and globals()
7. What is the output of this code? Answer: c
def f(): x=4 EXPLANATION: The function globals() returns a dictionary
x=1 of the module namespace, whereas the function locals()
f() returns a dictionary of the current namespace.
a) Error b) 4 c) Junk value d) 1