0% found this document useful (0 votes)
4 views9 pages

Python MCQ

The document contains a series of multiple-choice questions (MCQs) related to Python programming, covering topics such as language development, programming paradigms, syntax, functions, and built-in operations. Each question is followed by the correct answer and an explanation of the reasoning behind it. The content serves as a study guide for individuals preparing for Python-related assessments.

Uploaded by

dreamerayush1981
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views9 pages

Python MCQ

The document contains a series of multiple-choice questions (MCQs) related to Python programming, covering topics such as language development, programming paradigms, syntax, functions, and built-in operations. Each question is followed by the correct answer and an explanation of the reasoning behind it. The content serves as a study guide for individuals preparing for Python-related assessments.

Uploaded by

dreamerayush1981
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

Python MCQ (Multiple Choice Questions) d) None of the mentioned

Answer: d
1. Who developed Python Programming Language?
Explanation: Most keywords are in lowercase, but
a) Wick van Rossum
some like True, False, and None are capitalized.
b) Rasmus Lerdorf
c) Guido van Rossum 7. What will be the value of the following Python
d) Niene Stom expression?
Answer: c
print(4 + 3 % 5)
Explanation: Python language is designed by a
Dutch programmer Guido van Rossum in the a) 7
Netherlands. b) 2
c) 4
2. Which type of Programming does Python
d) 1
support?
Answer: a
a) object-oriented programming
Explanation: In Python, the modulus operator %
b) structured programming
has higher precedence than addition +. So, the
c) functional programming
expression is evaluated as 4 + (3 % 5), which is 4 +
d) all of the mentioned
3 = 7.
Answer: d
Explanation: Python is an interpreted programming 8. Which of the following is used to define a block
language, which supports object-oriented, of code in Python language?
structured, and functional programming. a) Indentation
b) Key
3. Is Python case sensitive when dealing with
c) Brackets
identifiers?
d) All of the mentioned
a) no
Answer: a
b) yes
Explanation: In Python, to define a block of code
c) machine dependent
we use indentation. Indentation refers to
d) none of the mentioned
whitespaces at the beginning of the line.
Answer: b
Explanation: Case is always significant while 9. Which keyword is used for function in Python
dealing with identifiers in python. language?
a) Function
4. Which of the following is the correct extension
b) def
of the Python file?
c) Fun
a) .python
d) Define
b) .pl
c) .py
d) .p Answer: b
Answer: c Explanation: The def keyword is used to create, (or
Explanation: ‘.py’ is the correct extension of the define) a function in python.
Python file. Python programs can be written in any
text editor. To save these programs we need to 10. Which of the following character is used to give
save in files with file extension ‘.py’. single-line comments in Python?
a) //
5. Is Python code compiled or interpreted? b) #
a) Python code is both compiled and interpreted c) !
b) Python code is neither compiled nor interpreted d) /*
c) Python code is only compiled Answer: b
d) Python code is only interpreted Explanation: To write single-line comments in
Answer: a Python use the Hash character (#) at the beginning
Explanation: Many languages have been of the line. It is also called number sign or pound
implemented using both compilers and sign. To write multi-line comments, close the text
interpreters, including C, Pascal, and Python. between triple quotes.
advertisement Example: “”” comment
text “””
6. All keywords in Python are in _________
a) Capitalized 11. What will be the output of the following
b) lower case Python code?
c) UPPER CASE i=1
while True: Division, Addition, Subtraction

if i%3 == 0:
Answer: d
break
Explanation: Python follows the PEMDAS rule
print(i) (similar to BODMAS): Parentheses, Exponentiation,
Multiplication/Division, then Addition/Subtraction.
i+=1 Operators at the same level are evaluated left to
a) 1 2 3 right.
b) SyntaxError 15. What will be the output of the following
c) 1 2 Python code snippet if x=1?
d) none of the mentioned
Answer: b x<<2
Explanation: The output will be a SyntaxError
a) 4
because i + = 1 is invalid syntax in Python. There
b) 2
should be no space between + and =. The correct
c) 1
syntax is i += 1.
d) 8
12. Which of the following functions can help us to
find the version of python that we are currently
Answer: a
working on?
Explanation: The binary form of 1 is 0001. The
a) sys.version(1)
expression x<<2 implies we are performing bitwise
b) sys.version(0)
left shift on x. This shift yields the value: 0100,
c) sys.version()
which is the binary form of the number 4.
d) sys.version
Answer: d 16. What does pip stand for python?
Explanation: The function sys.version can help us a) Pip Installs Python
to find the version of python that we are currently b) Pip Installs Packages
working on. It also contains information on the c) Preferred Installer Program
build number and compiler used. For example, d) All of the mentioned
3.5.2, 2.7.3 etc. this function also returns the Answer: c
current date, time, bits etc along with the version. Explanation: pip is a package manager for python.
Which is also called Preferred Installer Program.
13. Python supports the creation of anonymous
functions at runtime, using a construct called 17. Which of the following is true for variable
__________ names in Python?
a) pi a) underscore and ampersand are the only two
b) anonymous special characters allowed
c) lambda b) unlimited length
d) none of the mentioned c) all private members must have leading and
trailing underscores
d) none of the mentioned
Answer: c
18. What are the values of the following Python
Explanation: In Python, lambda functions are
expressions?
anonymous, meaning they don’t have a name.
They are defined using the lambda keyword and print(2**(3**2))
can take any number of arguments but only have
one expression. Lambdas are useful for creating print((2**3)**2)
small, throwaway functions quickly without print(2**3**2)
formally defining them using def.
a) 512, 64, 512
14. What is the order of precedence in python? b) 512, 512, 512
a) Exponential, Parentheses, Multiplication, c) 64, 512, 64
Division, Addition, Subtraction d) 64, 64, 64
b) Exponential, Parentheses, Division, Answer: a
Multiplication, Addition, Subtraction Explanation: Expression 1 is evaluated as: 2**9,
c) Parentheses, Exponential, Multiplication, which is equal to 512. Expression 2 is evaluated as
Addition, Division, Subtraction 8**2, which is equal to 64. The last expression is
d) Parentheses, Exponential, Multiplication, evaluated as 2**(3**2). This is because the
associativity of ** operator is from right to left. 23. The following python program can work with
Hence the result of the third expression is 512. ____ parameters.

19. Which of the following is the truncation def f(x):


division operator in Python?
def f1(*args, **kwargs):
a) |
b) // print("Sanfoundry")
c) /
d) % return x(*args, **kwargs)
Answer: b
return f1
Explanation: // is the operator for truncation
division. It is called so because it returns only the a) any number of
integer part of the quotient, truncating the decimal b) 0
part. For example: 20//3 = 6. c) 1
d) 2
20. What will be the output of the following
Python code?
Answer: a
l=[1, 0, 2, 0, 'hello', '', []]
Explanation: The decorator function f defines f1
print(list(filter(bool, l))) which uses *args and **kwargs to accept any
number of positional and keyword arguments. This
a) [1, 0, 2, ‘hello’, ”, []] allows the decorated function to work with any
b) Error number of parameters, making the decorator
c) [1, 2, ‘hello’] flexible.
d) [1, 0, 2, 0, ‘hello’, ”, []]
24. What will be the output of the following
Python function?
Answer: c
Explanation: The function filter(bool, l) removes all print(min(max(False,-3,-4), 2,7))
false elements from the list l, such as 0, ”, and [].
a) -4
The remaining true elements — 1, 2, and ‘hello’ —
b) -3
are returned as a new list.
c) 2
21. Which of the following functions is a built-in d) False
function in python?
a) factorial()
Answer: d
b) print()
Explanation: The max(False, -3, -4) evaluates to 0
c) seed()
because False is treated as 0, and 0 is greater than
d) sqrt()
-3 and -4. Then, min(0, 2, 7) returns 0. Since 0 is
equivalent to False, the output is False.
Answer: b
25. Which of the following is not a core data type
Explanation: The function seed is a function which
in Python programming?
is present in the random module. The functions
a) Tuples
sqrt and factorial are a part of the math module.
b) Lists
The print function is a built-in function which prints
c) Class
a value directly to the system output.
d) Dictionary
22. Which of the following is the use of id() Answer: c
function in python? Explanation: Class is a user-defined data type.
a) Every object doesn’t have a unique id
26. What will be the output of the following
b) Id returns the identity of the object
Python expression if x=56.236?
c) All of the mentioned
d) None of the mentioned print("%.2f"%x)
Answer: b
Explanation: The id() function in Python returns a) 56.236
the identity of an object. This identity is a unique b) 56.23
integer (or memory address) that remains constant c) 56.0000
for the object during its lifetime. Every object in d) 56.24
Python has a unique id, which helps in comparing
object references.
Answer: d b) a b c d
Explanation: The expression shown above rounds c) error
off the given number to the number of decimal d)
places specified. Since the expression given
A
specifies rounding off to two decimal places, the
output of this expression will be 56.24. Had the B
value been x=56.234 (last digit being any number
less than 5), the output would have been 56.23. C

27. Which of these is the definition for packages in D


Python?
a) A set of main modules
b) A folder of python modules Answer: d
c) A number of files containing Python definitions Explanation: In this code, x = ‘abcd’ is iterated over,
and statements and for each character i, i.upper() is called. The
d) A set of programs making use of Python upper() method returns a new string where all
modules characters are converted to uppercase. Each
uppercase character is then printed on a new line.
Therefore, the output is A, B, C, D, one per line.
Answer: b
Explanation: In Python, a package is defined as a 30. What is the order of namespaces in which
folder containing multiple Python modules, along Python looks for an identifier?
with a special __init__.py file that indicates the a) Python first searches the built-in namespace,
directory is a package. Packages help in organizing then the global namespace and finally the local
related modules into a single directory hierarchy, namespace
making the codebase more modular and b) Python first searches the built-in namespace,
manageable. then the local namespace and finally the global
namespace
28. What will be the output of the following c) Python first searches the local namespace, then
Python function? the global namespace and finally the built-in
print(len(["hello",2, 4, 6])) namespace
d) Python first searches the global namespace,
a) Error then the local namespace and finally the built-in
b) 6 namespace
c) 4 Answer: c
d) 3 Explanation: When Python encounters an identifier
(like a variable or function name), it follows the
LEGB rule to resolve it. It first looks in the Local
Answer: c
namespace (inside the current function), then in
Explanation: The len() function returns the number
the Enclosing namespace (if it’s a nested function),
of elements in the list, regardless of their types. In
followed by the Global namespace (top-level of the
this case, the list [“hello”, 2, 4, 6] contains four
module), and finally the Built-in namespace
elements, so len() returns 4.
(predefined functions like len(), sum(), etc.). So, the
29. What will be the output of the following correct search order for namespaces is: local →
Python code? global → built-in.

x = 'abcd' 31. What will be the output of the following


Python code snippet?
for i in x:
for i in [1, 2, 3, 4][::-1]:
print(i.upper())
print(i, end=' ')
a)
a) 4 3 2 1
a b) error
c) 1 2 3 4
B
d) none of the mentioned
C

D Answer: a
Explanation: The expression [1, 2, 3, 4][::-1] uses
slicing with a step of -1 to reverse the list. So the temp = tester(12)
list becomes [4, 3, 2, 1]. The for loop iterates over
print(temp.id)
this reversed list and prints each element, with
end=’ ‘ ensuring the output is on one line with a) 12
spaces in between. b) 224
c) None
32. What will be the output of the following
d) Error
Python statement?
Answer: a
print("a"+"bc") Explanation: When the tester class is instantiated
with temp = tester(12), the __init__ method is
a) bc
called. The id argument is passed as 12, and inside
b) abc
the __init__ method, self.id is assigned the string
c) a
value of id, which is “12”. However, the local
d) bca
variable id is reassigned to “224”, but this change
does not affect self.id, which retains the value “12”.
Answer: b 36. What will be the output of the following
Explanation: In Python, the + operator is used for Python program?
string concatenation. “a” + “bc” joins the two
strings together into a single string “abc”. def foo(x):

33. Which function is called when the following x[0] = ['def']


Python program is executed?
x[1] = ['abc']
f = foo()
return id(x)
format(f)
q = ['abc', 'def']
a) str()
print(id(q) == foo(q))
b) format()
c) __str__() a) Error
d) __format__() b) None
c) False
d) True
Answer: d
Answer: d
Explanation: When format(f) is executed, Python
Explanation: The list q is passed by reference to the
internally invokes the special method
function foo, so both x and q refer to the same
f.__format__(). This method controls how the
object in memory. The id() function returns the
object is formatted. The __str__() method is used
memory address of the object, which remains
by str(f), not format(f).
unchanged. Therefore, id(q) == foo(q) evaluates to
34. Which one of the following is not a keyword in True.
Python language?
37. Which module in the python standard library
a) pass
parses options received from the command line?
b) eval
a) getarg
c) assert
b) getopt
d) nonlocal
c) main
d) os
Answer: b
Explanation: eval can be used as a variable.
Answer: b
35. What will be the output of the following Explanation: The getopt module in Python’s
Python code? standard library is used to parse command-line
options and arguments. It allows the script to
class tester: accept flags and parameters (like -h or –help)
similar to those in shell scripts. For example:
def __init__(self, id):
import getopt, sys
self.id = str(id)
opts, args = getopt.getopt(sys.argv[1:], "h",
id="224"
["help"])
This line parses short option -h and long option – 42. What will be the value of ‘result’ in following
help. Python program?

38. What will be the output of the following list1 = [1,2,3,4]


Python program?
list2 = [2,4,5,6]
z=set('abc')
list3 = [2,6,7,8]
z.add('san')
result = list()
z.update(set(['p', 'q']))
result.extend(i for i in list1 if i not in (list2+list3)
print(z) and i not in result)

a) {‘a’, ‘c’, ‘c’, ‘p’, ‘q’, ‘s’, ‘a’, ‘n’} result.extend(i for i in list2 if i not in (list1+list3)
b) {‘abc’, ‘p’, ‘q’, ‘san’} and i not in result)
c) {‘a’, ‘b’, ‘c’, ‘p’, ‘q’, ‘san’}
result.extend(i for i in list3 if i not in (list1+list2)
d) {‘a’, ‘b’, ‘c’, [‘p’, ‘q’], ‘san}
and i not in result)

print(result)
Answer: c
Explanation: The code shown first adds the a) [1, 3, 5, 7, 8]
element ‘san’ to the set z. The set z is then b) [1, 7, 8]
updated and two more elements, namely, ‘p’ and c) [1, 2, 4, 7, 8]
‘q’ are added to it. Hence the output is: {‘a’, ‘b’, ‘c’, d) error
‘p’, ‘q’, ‘san’}

39. What arithmetic operators cannot be used with Answer: a


strings in Python? Explanation: Here, ‘result’ is a list which is
a) * extending three times. When first time ‘extend’
b) – function is called for ‘result’, the inner code
c) + generates a generator object, which is further used
d) All of the mentioned in ‘extend’ function. This generator object contains
the values which are in ‘list1’ only (not in ‘list2’ and
‘list3’).
Answer: b
Same is happening in second and third call of
Explanation: + is used to concatenate and * is used
‘extend’ function in these generator object
to multiply strings.
contains values only in ‘list2’ and ‘list3’
40. What will be the output of the following respectively.
Python code? So, ‘result’ variable will contain elements which are
only in one list (not more than 1 list).
print("abc. DEF".capitalize())
43. To add a new element to a list we use which
a) Abc. def Python command?
b) abc. def a) list1.addEnd(5)
c) Abc. Def b) list1.addLast(5)
d) ABC. DEF c) list1.append(5)
d) list1.add(5)
Answer: a
Explanation: The first letter of the string is Answer: c
converted to uppercase and the others are Explanation: We use the function append to add
converted to lowercase. an element to the list.
41. Which of the following statements is used to 44. What will be the output of the following
create an empty set in Python? Python code?
a) ( )
b) [ ] print('*', "abcde".center(6), '*', sep='')
c) { }
a) * abcde *
d) set()
b) *abcde *
c) * abcde*
d) * abcde * 48. What is the maximum possible length of an
identifier in Python?
a) 79 characters
Answer: b b) 31 characters
Explanation: Padding is done towards the right- c) 63 characters
hand-side first when the final string is of even d) none of the mentioned
length. Answer: d
45. What will be the output of the following Explanation: In Python, identifiers can be of any
Python code? length. There is no fixed maximum, though
extremely long names are not practical.
list1 = [1, 3]
49. What will be the output of the following
list2 = list1 Python program?

list1[0] = 4 i=0

print(list2) while i < 5:

a) [1, 4] print(i)
b) [1, 3, 4]
c) [4, 3] i += 1
d) [1, 3] if i == 3:

break
Answer: c
Explanation: In the code, list2 = list1 creates a else:
reference to the same list in memory. So when
print(0)
list1[0] is changed to 4, list2 also reflects that
change. The output is [4, 3]. a) error
b)
46. Which one of the following is the use of
function in python? 0
a) Functions don’t provide better modularity for
1
your application
b) you can’t also create your own functions 2
c) Functions are reusable pieces of programs
d) All of the mentioned 3

0
Answer: c c)
Explanation: Functions are reusable pieces of
programs. They allow you to give a name to a block 0
of statements, allowing you to run that block using
1
the specified name anywhere in your program and
any number of times. 2
47. Which of the following Python statements will d) none of the mentioned
result in the output: 6?

A = [[1, 2, 3], Answer: c


[4, 5, 6], Explanation: In this code, the while loop iterates
from i = 0 to i = 2, printing the values of i. When i
[7, 8, 9]] becomes 3, the if i == 3 condition is met, and the
break statement is executed, which terminates the
a) A[2][1]
loop early. Since the loop was terminated using
b) A[1][2]
break, the else block is not executed. Therefore,
c) A[3][2]
the output is 0, 1, and 2.
d) A[2][3]
Answer: b 50. What will be the output of the following
Explanation: The output that is required is 6, that Python code?
is, row 2, item 3. This position is represented by
the statement: A[1][2]. x = 'abcd'
for i in range(len(x)): z=set('abc$de')

print(i) print('a' in z)

a) error a) Error
b) 1 2 3 4 b) True
c) a b c d c) False
d) 0 1 2 3 d) No output

Answer: d Answer: b
Explanation: i takes values 0, 1, 2 and 3. Explanation: The code shown above is used to
check whether a particular item is a part of a given
51. What are the two main types of functions in
set or not. Since ‘a’ is a part of the set z, the output
Python?
is true. Note that this code would result in an error
a) System function
in the absence of the quotes.
b) Custom function
c) Built-in function & User defined function 55. What will be the output of the following
d) User function Python expression?
Answer: c
print(round(4.576))
Explanation: Built-in functions and user defined
ones. The built-in functions are part of the Python a) 4
language. Examples are: dir(), len() or abs(). The b) 4.6
user defined functions are functions created with c) 5
the def keyword. d) 4.5
52. What will be the output of the following
Python program? Answer: c
def addItem(listParam): Explanation: The round() function rounds the
number to the nearest integer by default. Since
listParam += [1] 4.576 is closer to 5 than 4, round(4.576) returns 5.
Therefore, the output is 5.

56. Which of the following is a feature of Python


mylist = [1, 2, 3, 4]
DocString?
addItem(mylist) a) In Python all functions should have a docstring
b) Docstrings can be accessed by the __doc__
print(len(mylist)) attribute on objects
a) 5 c) It provides a convenient way of associating
b) 8 documentation with Python modules, functions,
c) 2 classes, and methods
d) 1 d) All of the mentioned
Answer: a
Explanation: The function addItem uses += [1] to
Answer: d
modify the list passed to it. Since lists are mutable
Explanation: Python has a nifty feature called
and passed by reference, mylist is modified
documentation strings, usually referred to by its
directly. After appending 1, it becomes [1, 2, 3, 4,
shorter name docstrings. DocStrings are an
1], so its length is 5.
important tool that you should make use of since it
53. Which of the following is a Python tuple? helps to document the program better and makes
a) {1, 2, 3} it easier to understand.
b) {}
57. What will be the output of the following
c) [1, 2, 3]
Python code?
d) (1, 2, 3)
Answer: d print("Hello {0[0]} and {0[1]}".format(('foo', 'bin')))
Explanation: A tuple in Python is an immutable
a) Hello (‘foo’, ‘bin’) and (‘foo’, ‘bin’)
sequence type and is defined using round brackets
b) Error
( ). For example, (1, 2, 3) is a tuple.
c) Hello foo and bin
54. What will be the output of the following d) None of the mentioned
Python code snippet? Answer: c
Explanation: The output of the code is Hello foo try:
and bin. Here, the format string uses index-based
return 1
access to retrieve elements from the tuple passed
as a single argument. {0[0]} and {0[1]} access the finally:
first and second elements of the tuple respectively.
return 2
58. What is output of print(math.pow(3, 2))?
a) 9.0 k = foo()
b) None
print(k)
c) 9
d) None of the mentioned a) error, there is more than one return statement
Answer: a in a single try-finally block
Explanation: math.pow() returns a floating point b) 3
number. c) 2
d) 1
59. Which of the following is the use of id()
Answer: c
function in python?
Explanation: In Python, if both the try block and
a) Every object in Python doesn’t have a unique id
the finally block contain return statements, the
b) In Python Id function returns the identity of the
return in the finally block overrides the one in the
object
try block. So, even though return 1 is in the try, the
c) None of the mentioned
function ends up returning 2 because of the finally
d) All of the mentioned
block.
Answer: b
Explanation: Each object in Python has a unique id.
The id() function returns the object’s id.

60. What will be the output of the following


Python code?

x = [[0], [1]]

print((' '.join(list(map(str, x))),))

a) 01
b) [0] [1]
c) (’01’)
d) (‘[0] [1]’,)
Answer: d
Explanation: In this code, map(str, x) converts each
inner list [0] and [1] into strings: “[0]” and “[1]”.
Then ‘ ‘.join(…) creates the string “[0] [1]”. Finally, it
is wrapped in a tuple using the comma syntax,
resulting in (‘[0] [1]’,).

61. The process of pickling in Python includes


____________
a) conversion of a Python object hierarchy into
byte stream
b) conversion of a datatable into a list
c) conversion of a byte stream into Python object
hierarchy
d) conversion of a list into a datatable
Answer: a
Explanation: Pickling is the process of serializing a
Python object, that is, conversion of a Python
object hierarchy into a byte stream. The reverse of
this process is known as unpickling.

62. What will be the output of the following


Python code?

def foo():

You might also like