Python MCQs
1. What is the type of each element in sys.argv?
a) set
b) list
c) tuple
d) string
View Answer
Answer: d
Explanation: It is a list of strings.
2. What is the length of sys.argv?
a) number of arguments
b) number of arguments + 1
c) number of arguments – 1
d) none of the mentioned
View Answer
Answer: b
Explanation: The first argument is the name of the program itself. Therefore the length of sys.argv is one more than the number arguments.
3. What will be the output of the following Python code?
def foo(k): k[0] = 1 q = [0] foo(q) print(q)
a) [0]
b) [1]
c) [1, 0]
d) [0, 1]
View Answer
Answer: b
Explanation: Lists are passed by reference.
4. How are keyword arguments specified in the function heading?
a) one-star followed by a valid identifier
b) one underscore followed by a valid identifier
c) two stars followed by a valid identifier
d) two underscores followed by a valid identifier
View Answer
Answer: c
Explanation: Refer documentation.
5. How many keyword arguments can be passed to a function in a single function call?
a) zero
b) one
c) zero or more
d) one or more
View Answer
Answer: c
Explanation: Zero keyword arguments may be passed if all the arguments have default values.
6. What will be the output of the following Python code?
def foo(fname, val): print(fname(val)) foo(max, [1, 2, 3]) foo(min, [1, 2, 3])
a) 3 1
b) 1 3
c) error
d) none of the mentioned
View Answer
Answer: a
Explanation: It is possible to pass function names as arguments to other functions.
7. What will be the output of the following Python code?
def foo(): return total + 1 total = 0 print(foo())
a) 0
b) 1
c) error
d) none of the mentioned
View Answer
Answer: b
Explanation: It is possible to read the value of a global variable directly.
8. What will be the output of the following Python code?
def foo(): total += 1 return total total = 0 print(foo())
a) 0
b) 1
c) error
d) none of the mentioned
View Answer
Answer: c
Explanation: It is not possible to change the value of a global variable without explicitly specifying it.
9. What will be the output of the following Python code?
def foo(x): x = ['def', 'abc'] return id(x) q = ['abc', 'def'] print(id(q) == foo(q))
a) True
b) False
c) None
d) Error
View Answer
Answer: b
Explanation: A new object is created in the function.
10. What will be the output of the following Python code?
def foo(i, x=[]): x.append(i) return x for i in range(3): print(foo(i))
a) [0] [1] [2]
b) [0] [0, 1] [0, 1, 2]
c) [1] [2] [3]
d) [1] [1, 2] [1, 2, 3]
View Answer
Answer: b
Explanation: When a list is a default value, the same list will be reused.