Python MCQs

Python MCQs

These Python multiple-choice questions and their answers will help you strengthen your grip on the subject of Python. You can prepare for an upcoming exam or job interview with these 800+ Python MCQs.
So scroll down and start answering.

1: What is a correct term for the following piece of Python syntax: 3 + 4

A.   A statement.

B.   A lambda.

C.   A closure.

D.   A suite.

E.   An expression.

2: What would be printed? x = [[1, 2], [3, 4], [5, 6]] x = [x for x in x for x in x] print x

A.   [[1, 2], [1, 2], [1, 2]]

B.   Compilation error

C.   [1, 2, 3, 4, 5, 6]

D.   [6, 6, 6, 6, 6, 6]

E.   [[1, 2], [3, 4], [5, 6]]

3: From which module can a user import classes and methods to work with regular expressions?

A.   sys

B.   re

C.   regularexpressions

D.   regexp

4: What is the exponentiation (power) operator?

A.   **

B.   ^

C.   Both are correct.

D.   None are correct.

5: What are wxPython, pyQT, and pyGTK?

A.   System administrators' toolkits for Python

B.   GUI programming toolkits for Python

C.   Test suites for Python

D.   Names of popular Python repositories

6: What is the difference between using single quotes and double quotes in Python strings?

A.   Single quotes are for short strings. Double quotes are for long strings.

B.   There is no difference.

C.   Double quotes are for constants. Single quotes are for variables.

D.   In Python you can use only single quotes.

7: What will typing the following at the Python interpreter produce? [3]*3

A.   '9'

B.   [9]

C.   '333'

D.   [3, 3, 3]

8: Which of these values equates to True?

A.   ()

B.   None of these

C.   ""

D.   {}

9: Functions are first-class objects in Python.

A.   Always

B.   Never

10: It is possible to create a while loop that will never stop?

A.   Yes

B.   No

11: Python variables are references to objects.

A.   Always

B.   Never

12: Python files typically have which extension?

A.   py

B.   pl

C.   pt

D.   pie

E.   pil

13: What is the index of the first item in a tuple or list?

A.   0

B.   1

C.   -2,147,483,648

D.   -1

14: What is the purpose of an 'if' statement?

A.   Repeatedly execute a block of code

B.   Conditionally execute a block of code

C.   Execute code from more than one place in a program

15: If you want a function you define to return "a", what should be put on the last line of the function (correctly indented)?

A.   "a"

B.   ret("a")

C.   return "a"

D.   a

16: What will be printed as the result of: animals = ['bear', 'tiger', 'penguin', 'zebra'] print animals[2] ?

A.   bear

B.   tiger

C.   penguin

D.   zebra

17: What character is used to denote the beginning of a comment?

A.   //

B.   {

C.   /*

D.   #

18: How does one print the string "fred" on a line by itself in Python 2.x?

A.   print 'fred'

B.   println('fred')

C.   cout << "fred" << endl;

D.   write('fred')

19: Which Python implementation is best for testing Java code?

A.   CPython

B.   IronPython

C.   Jython

D.   PyPy

20: True or False: Python holds the current working directory in memory.

A.   False

B.   True

21: True or False. in python you can run linux command

A.   False

B.   True

22: What keyword is needed to use an external module?

A.   use

B.   package

C.   external

D.   import

23: What does the sys module include?

A.   All are correct.

B.   The name of the operating system where your Python code is run.

C.   The largest integer the machine's architecture supports.

D.   The Python interpreter's version number.

24: What is the maximum recursion limit in Python?

A.   It's configurable.

B.   100000

C.   100

D.   10000

E.   1000000

25: What will be the value of a variable x after executing the expression x = y = 1?

A.   This expression will result in a syntax error.

B.   Undefined

C.   0

D.   1

26: Which of the following data structures supports the 'in' operator: list, dictionary, set ?

A.   None.

B.   set

C.   list

D.   dictionary

E.   All three.

27: When opening the Python shell, the prompt you see is

A.   >

B.   #

C.   $

D.   >>>

28: What kind of type system does Python have?

A.   Dynamic.

B.   Inverse.

C.   Loading.

D.   Proportional.

E.   Static.

29: Is it possible to call a function from within another function?

A.   Yes, but only in the interactive shell.

B.   Yes, but only when the program runs on a remote server.

C.   Yes.

D.   No.

30: What data type is the following: [1, 2, 3] ?

A.   Counter.

B.   List.

C.   Dictionary.

D.   Tuple.

E.   Set.

31: What does the print statement do?

A.   Returns the status of all printers installed on the network.

B.   Evaluates its parameters and writes the resulting objects to standard output.

C.   Allows users to input data.

D.   Prints the source code on the default printer.

32: What function do you use to determine the size of a tuple, a list, or a string?

A.   len

B.   length

C.   size

D.   Tuplen for tuples, listlen for lists, strlen for strings

33: How are comments denoted in Python?

A.   <!-- text -->

B.   # text

C.   // text

D.   /* text */

E.   ^^ text ^^

34: What is a string delimited by?

A.   "

B.   """

C.   '''

D.   All of these are correct,

E.   '

35: What does the expression string1 + string2 do?

A.   Repeats string1 string2 times (string2 must be in numeric format).

B.   Concatenates string1 and string2.

C.   It's a syntax error.

D.   Adds string1 to string2 (both must be in numeric format).

36: Which of these will result in an error?

A.   "hello" * 2

B.   "hello" ** 2

C.   len ( "hello" )

D.   "hello" + "hello"

37: What is a variable?

A.   A statement which allows you to choose one variant from a given set

B.   A collection of elements, each identified by an index

C.   An object which may contain some data

D.   An object containing data whose value cannot be altered by the program

38: What operator checks the inequality of two values?

A.   !=

B.   isn't

C.   =/=

D.   ><

E.   >=

39: How are non-anonymous Python functions declared?

A.   With the "function" keyword.

B.   With the "def" keyword.

C.   With function prototypes declared in header files.

D.   With "do function ... done".

40: Which one of following Internet protocols is supported by Python libraries: HTTP, FTP, SMTP, POP3, IMAP4, NNTP, Telnet?

A.   Only HTTP

B.   Only HTTP, FTP, POP3, IMAP4

C.   None of them

D.   All of them

41: When defining a class, what controls which parameters that may be passed when the class is instantiated?

A.   There is no way to pass parameters to a class instance.

B.   Specifying those parameters after the class name.

C.   Specifying those parameters in the definition of an __init__ method of the class.

D.   Writing the desired values after the class name when the class instance is created.

42: What is the del statement used for?

A.   To remove a function from a list given its name.

B.   To remove an item from a list given its index.

C.   To delete a file from the file system given its path.

D.   To delete a user if you are a privileged user.

43: The statement 'a,b = b,a' is a valid way to successfuly switch the values of the variables a and b in Python.

A.   False

B.   True

44: How would you declare a list x in Python with predefined values of 1, 2 and 3 ?

A.   x = list{'1', '2', '3'}

B.   x = list(1, 2, 3)

C.   x = {'1', '2', '3'}

D.   x = [1, 2, 3]

E.   x = new list (1, 2, 3)

45: Which of the following is NOT a valid part of an "if" block?

A.   elseif:

B.   elif:

C.   if:

D.   else:

46: How does one pause the execution of a program for 5 seconds?

A.   import date date.pause(5)

B.   import time time.sleep(5)

C.   import date date.pause(5.0)

47: What is the value of the variable a after the following statement: a=(1,2,3); a=a[2];

A.   2

B.   None and the system generates an error (exception)

C.   None

D.   1

E.   3

48: Which of these lines properly checks the length of a variable named "l"?

A.   l.len()

B.   len(l)

C.   length(l)

D.   l.length()

49: If i and j are numbers, which statement evaluates to the remainder of i divided by j?

A.   i mod j

B.   i % j

C.   i // j

D.   i / j

50: How do you print from 0 to 10 in python?

A.   for i in range(11): print i

B.   for( x = 0; x < 11; x++) printf("%s",x);

C.   while x < 10: print x

D.   for i in range(10): print i

51: The range(n) function returns values from...

A.   0 to n-1

B.   0 to n

C.   n-1 to n

D.   Syntax error: missing arguments

52: there is a code example: x = {"quizful": []} How can you add an element "python test" in list "quizful"?

A.   x["quizful"][] = "python test"

B.   x["quizful"].append("python test")

C.   x["quizful"].add("python test")

D.   x["quizful"] += "python test"

53: PEP8 style guidelines include:

A.   Use 4 spaces per indentation level

B.   Don't use spaces around the '=' sign when used to indicate a keyword argument or a default parameter value

C.   CapWords for class names, lowercase for function names

D.   All of these

E.   Limit all lines to a maximum of 79 characters

54: How can the elements in a list be reversed?

A.   list_.flip()

B.   list_ = list_[-1::]

C.   list_.reverse()

D.   list_[-1:-len(a)]

55: Given the list "li = ["a", "Sir Robin", "Sir Gawaine", "Sir Not Appearing in this film", "cb", "rabbits"]", what does the following list comprehension return "[item for item in li if len(item) > 2]"?

A.   ['Sir Robin', 'Sir Gawaine', 'Sir Not Appearing in this film']

B.   4

C.   ['Sir Robin', 'Sir Gawaine', 'Sir Not Appearing in this film', 'rabbits']

D.   ['Sir Robin', 'Sir Gawaine', 'Sir Not Appearing in this film', 'cb', 'rabbits']

E.   True

56: What function is used to convert integer numbers to floats?

A.   floatize

B.   float

C.   int_to_float

D.   int2float

57: What is a fundamental difference between a list and a tuple?

A.   Lists have no length limit.

B.   Lists can be nested, tuples not.

C.   Lists can be mutated, while tuples cannot.

D.   Lists cannot be mutated, while tuples can.

E.   Only list can be subclassed.

58: What does a function definition header end with?

A.   :

B.   nothing

C.   end of line

59: Assume dictionary mydict = {'foo': 'Hello', 'bar': 'World!'} Which of the below would change the value of foo to 'Goodbye' ?

A.   mydict.update('foo', 'Goodbye')

B.   mydict[foo] = 'Goodbye'

C.   mydict.foo.update('Goodbye')

D.   mydict['foo'] = 'Goodbye'

E.   mydict.foo = 'Goodbye'

60: What is the name of a feature invoked by the following: "This is a string"[3:9]

A.   Multi-indexing

B.   Pieces

C.   Pathfinding

D.   Slices

61: Does the elif statement require a logical expression?

A.   No, there is no elif statement in Python

B.   Yes

C.   No

D.   Yes, unless it is used in place of an else statement

62: What is the type of the expression [" "]?

A.   array

B.   string

C.   tuple

D.   list

63: According to PEP8 python programs should generally be indented with:

A.   2 spaces

B.   8 spaces

C.   1 tab

D.   4 spaces

64: What will be result of 3/2 in Python 2.x?

A.   2

B.   1.5

C.   1

65: Is it possible to catch AssertionError exceptions?

A.   Yes

B.   Yes, but only when not in Python's interactive shell

C.   Yes, but only in Python's interactive shell

D.   No

66: What is a string in Python?

A.   An object which is a sequence of characters

B.   Any text put in double-quotes

C.   The same thing as a statement, just an argument

D.   A line of source code

67: What is the statement that can be used in Python if a statement is required syntactically but the program requires no action?

A.   pass

B.   return

C.   yield

D.   continue

E.   break

68: True or False? you can create Android programs with Python.

A.   True

B.   False

69: What is the main difference between a tuple and a list?

A.   Tuples are created with parentheses and lists are create with square brackets.

B.   Tuples are created with square brackets and lists are create with square with parentheses.

C.   Tuples can contain no more than 16 elements, lists can contain more than that.

D.   Lists are changeable sequences of data, while tuples are not changeable.

70: What will happen if you try to add an integer to a long number?

A.   The result will be an integer.

B.   The result of this operation is undefined.

C.   The result will be a long number.

D.   Python will warn you about a type mismatch and ask if you want to convert an integer to a long.

E.   This operation will result in an overflow error.

71: Which of these lines will return 125?

A.   Math.pow( 5, 3)

B.   5 ^ 3

C.   pow( "5 ^ 3")

D.   5 ** 3

72: What will typing the following at the Python interpreter produce? >>> url = 'http://docs.python.org' >>> url[-4:]

A.   '.org'

B.   IndexError: string index out of range

C.   'http'

D.   'python.org'

E.   'docs'

73: True or False; you can't create async program in python

A.   False

B.   True

74: If variables a and b are initialized using an assignment (a, b) = (4, 6), what value will be stored in a variable c by using a statement c = eval("a*b")?

A.   444444

B.   This statement will result in a syntax error.

C.   "a*b"

D.   24

75: What does the pass statement do?

A.   Nothing. It can be used when a statement is needed syntactically.

B.   Jumps to the top of the closest enclosing loop.

C.   There is no such statement in Python.

D.   It passes control flow of the program to the debugger.

E.   It is a function which asks the user to enter a password.

76: What is used to read the next line in a file up to the '\n'?

A.   open('file').readline()

B.   open('file').read('\n')

C.   open('file').read()

D.   open('file').readlines()

77: What will typing the following at the Python interpreter produce? sequence = ['A','B','C','D','E','F'] ; sequence[-6]

A.   'F'

B.   'B'

C.   IndexError exception

D.   'A'

78: Given the following assignment: s = ('xxx', 'abcxxxabc', 'xyx', 'abc', 'x.x', 'axa', 'axxxxa', 'axxya'), what is the result of the expression filter ((lambda s: re.search(r'xxx', s)), s)?

A.   This expression will result in a syntax error.

B.   ('x.x')

C.   ('xxx', 'abcxxxabc', 'axxxxa')

D.   ('xxx')

79: Assume myList = [1, 2, 3, 4, 5] and myVar = 3 How would you check if myVar is contained in myList?

A.   myList.has_item(myVar)

B.   myList.contains(myVar)

C.   myVar.exists(myList)

D.   myVar in myList

E.   myVar.in(myList)

80: By convention, where are internal variables set in a Python class?

A.   the __class__ function

B.   the __init__ function

C.   global variables

D.   the init function

81: Where does 'pip install' retrieve modules from?

A.   'pip' does not have an 'install' subcommand

B.   $PIP_PKG_DIR - your local database of Python packages (by default /var/cache/pip on UNIX and C:\pypackaging\pip on Windows)

C.   PyPI - the Python Package Index

D.   packages.debian.org - the Debian package archive

E.   the lowest-latency Sourceforge download mirror

82: A decorator in python ________

A.   Provides static documentation about an object.

B.   reformats a source code according to python formatting rules

C.   dynamically alters the functionality of a function, method, or class.

D.   is a sub-class on object in an inherited class

83: How is a default value to a function's parameter provided?

A.   It is impossible to provide a default value to a function's parameter.

B.   By writing the desired value in parentheses after the parameter's name.

C.   By writing the desired value in curly brackets after the parameter's name.

D.   By writing an equal sign after the parameter's name and then the desired value.

84: How would you assign the last element of a list to the variable 'x' without modifying the list?

A.   x = last(aList)

B.   x = aList[-1]

C.   x = aList.pop()

D.   x = aList.last()

85: Which keywords can be used to define a function?

A.   def, lambda

B.   def, defun

C.   def, letrec

D.   def, proc

E.   def, import

86: How can each line of an already-opened text file be printed?

A.   cat file_

B.   for line in file_: print line

C.   while True: if not line: break line = file_.readline()

D.   print file_

87: Which of the following is not a valid data type in Python?

A.   str

B.   float

C.   int

D.   double

E.   bool

88: Why might a Python module have the following code at the end: if __name__ == '__main__'?

A.   Code that is written after this statement is executed only when the module is used directly.

B.   Code that is written after this statement is ignored by the interpreter, so comments are usually added after it.

C.   Some of the viruses that infect Python files do not affect modules with such a statement.

D.   This code prevents a module from being executed directly.

89: Which of these two operations can be applied to a string: +, * ?

A.   Both of them.

B.   Only +

C.   Only *

D.   Neither.

90: How can you open a binary file named dino?

A.   fopen 'dino', 'r'

B.   open('dino', 'r')

C.   open 'dino', 'r'

D.   open('dino', 'rb')

91: If you want to enter accented characters, what is put in front of the string the character?

A.   d

B.   g

C.   G

D.   u

92: Is it possible to swap values of variables a and b by using the expression 'a, b = b, a' ?

A.   Yes, but only for string variables

B.   Yes, but only for numeric variables

C.   It is always possible.

D.   No.

93: What does the expression "(lambda x: x + 3)(1)" return?

A.   'lambda lambda lambda'

B.   An anonymous function.

C.   A syntax error.

D.   13

E.   4

94: What is a package?

A.   Any Python program which imports external modules.

B.   All Python programs that are available on the computer.

C.   A folder with module files that can be imported together.

D.   Any folder with Python source code files in it.

95: Which example would return "Python Supremacy"?

A.   "Python _".find("_", "Supremacy")

B.   "Python _".replace("_", "Supremacy")

C.   "Python _".substitute("_", "Supremacy")

96: What syntax do you use when you create a subclass of an existing class?

A.   You cannot extend classes in Python

B.   SubclassName is subclass of BasicClassName

C.   class SubclassName(BasicClassName):

D.   class BasicClassName(SubclassName):

97: What is the correct form for the first line of the switch operator?

A.   There is no switch operator in Python

B.   switch?

C.   switch

D.   switch:

98: The 'distutils' module provides

A.   the packaging tools for Python

B.   utility functions for calculating distance

C.   utility functions for higher order math functions.

99: What would be the result of: print not (True or False) ?

A.   TRUE

B.   1

C.   0

D.   False

100: What is the result of string.lower('RR')?

A.   RR'

B.   'lower'

C.   an AttributeError exception

D.   rr

E.   'rr'