Python Quiz Answers

1.  What is an iterator in Python?

A)  A stream of data that is manipulated or interacted with as an object.
B)  A function that returns a namespace.
C)  A module of nested objects.
D)  A function that returns packages.

Answer: A. For more information, see the Python.org glossary.

2.  Which module in Python allows you to translate strings to and from binary formats?

A)  Marshal
B)  Shelve
C)  Pickle
D)  DMAC

Answer: A. For more information, see the official Python.org site here.

3.  Which of the following is a Rich Internet Application toolkit?

A) binascii
B) shelve
C) pyjamas
D) alglib

Answer:  C. For more information, see page 362 of Programming Python: Powerful Object-Oriented Programming(4th Edition) by Mark Lutz, published by O'Reilly in 2011.

4.  Which of the following provides an interface to AWS?

A) binascii
B) botocore
C) sndhdr
D) xdrlib

Answer: B.  For more information, see this external link.

5.  How does Python store an error?

A)  As a static variable inside the interpreter
B)  It normally uses an operating system environmental variable.  But if there were too many arguments, it writes to a buffer outside the interpreter.
C)  Inside a pseudo class file (.pyc) in /tmp/
D)  It raises the error to the exception logger outside of the interpreter
E)  In the internal sqlite database

Answer: A. For more information, see the official Python explanation.

6.  What does the yield keyword do in Python?

A)  It is a CPython mechanism to synchronize threads.
B)  A reserved word to control the flow of execution to support conditional logic with Python generators.
C)  A reserved word that pauses a function from parsing named tuples.
D)  It sets null points to evaluate as zeroes in arithmetic operations.

Answer: B.  For more information, see the Python.org glossary.

7.  Which of the following can allow for non-destructive testing of whether an exception has been set?

A)  pyyaml and pypy modules
B)  PyErr_Config()
C)  PyErr_Clear()
D)  PyErr_Occurred()

Answer: D. For more information, see this official Python document for an explanation.

8.  If you are receiving an error with a Python program that attempts to connect to a network resource with SSL, there is a way to avoid an error.  This error is '"SSL: CERTIFICATE_VERIFY_FAILED" Error'
One workaround involves these two lines of Python code:

import ssl
ssl._create_default_https_context = ssl._create_unverified_context

Which of the following most nearly addresses the above two-line solution:

A)  The solution makes the Python program more secure.
B)  The solution makes use of the sys library.
C)  The solution is very inadvisable.
D)  The solution would never work.

Answer:  C.  For more information, see this posting.

9.  What is a generator in Python?

A)  Any class that is a factory design pattern.
B)  A reserved word that is a parent class of all iterators in the program.
C)  An object that controls the CPU of the Python Just-In-Time compiler.
D)  A function that has a yield statement and returns an iterator.

Answer:  D.  For more information, see this external site.

10.  Which two of the following add to thread safety in Python (so different threads do not modify data to have unexpected results)?

A)  metaclass
B)  global interpreter lock
C)  trash collection
D)  overwatch
E)  duck-typing
F)  lbyl
G)  lambda
H)  list comprehension
I)  Pythonic sequence
J)  object slice

Answer:  A) and B)  For more information, see this python.org link.

11.  When trying to install pycrypto you run this:

python setup.py build

and you receive an error like this "warning: GMP or MPIR library not found; Not building Crypto.PublicKey._fastmath." what does it mean?

A) You cannot proceed with installing pycrypto; the installation has been aborted.
B) You can proceed with installing pycrypto; the installation may still work.
C) You have a Python Fabric vulnerability
D) A German edition of pycrypto was already installed and you may or may not be able to proceed.

Answer: B.  You may move on to "python setup.py install".  To be on the safe side, you may want to investigate why the error is happening.  Here is a related external link.

12.  How do you find the version of Tornado (python-tornado) on a RedHat server?

A)  python
>>> print python-tornado.version_info

B)  python
>>> import tornado
>>> print tornado.version_info

C)  which python-tornado

D)  python-tornado --version

Answer:  B

13.  What does GIL stand for?

A)  Gears Interpreting Language
B)  Good Invention Language
C)  Global Interpreter Lock
D)  Generate Interprocess Loquitur
E)  Global Instant Lookup

Answer:  C. Source is page 1564 of Programming Python: Powerful Object-Oriented Programming by Mark Lutz.  Published by O'Reilly.

14.  Where does the "kw" come from or mean in the **kwargs you see in Python error messages and/or code?

A)  kilowatt (wildcard kilowatt arguments)
B)  You hear stars on the radio.  Radio stations on the West Coast of the U.S. traditionally have call signs that start with the letter "k," and radio stations on the East Coast have call signs that start with the letter "w."  For a radio button to appear in a GUI written in Python, there needs to be arguments. 
C)  keyword
D)  keep working

Answer: C.  **args is for iterable objects (e.g., a list).  **kwargs is for key-worded pairs (e.g., a dictionary).  For more information see this external link.

15. How many different directory locations does the "import" command look to for a .py file when invoked?

A) 0
B) 1
C) 2
D) Often several but it depends

Answer: D. For more information, see this posting.

16. True or False? A function in Python has to have a return statement.

Answer: False. If you want more information, see this posting.

17. What is a common way (as of 2019) to start a new thread in Python assuming the proper module has been imported? Choose two.

A) nameofthread = Thread(nameoffunction)
B) nameofthread = start_new(nameoffucntion)
C) thread.start_new(nameoffunction)
D) thread.start_new_thread(nameoffunction)
E) nameofthread = newthread()

Answer: A and D.

We found this works:

from threading import Thread

def contint():
  print("Hello!")

if __name__ == "__main__":
    thread = Thread(contint())
    thread.start()
    thread.join()
    print("thread finished...exiting")

We found this works:

import _thread as thread 
def contint():
   print("Hello!")
if name == "main":
     foobar = thread.start_new_thread(contint, () )
     print("thread finished…exiting")

18. What percentage of data types and classes in Python are objects?

A) 0%
B) 25%
C) 50%
D) 75%
E) 100%

Answer: E. The source of this is here. n.b. Python is not a purely object-oriented language because of the way it handles encapsulation. If you want to read more about this, see this Quora answer or this analyticbridge website page.

19. What is a function decorator in Python?

A) A function that uses a function as a parameter and returns a function with a special @ syntax.
B) A function that uses a function as a parameter and returns a function with a special ^ syntax.
C) An anonymous function that passes along parameters.
D) A library module that enhances GUI Python programming.
E) A library module that obfuscates system functions programming.

Answer: A. See this posting for more information.

20. What is the recommended way of calling subprocesses in Python 3.5 or higher?

A) Using the os.exec function.
B) Using the os.spawn function.
C) Using the subprocess.open function.
D) Using the subprocess.run() function.

Answer: D. Source: https://docs.python.org/3/library/subprocess.html
Here is an example:

python
>>> from subprocess import PIPE
>>> subprocess.run(["ls", "-l", "/dev/null"], stdout=PIPE, stderr=PIPE)

21. Without "import re" using Python 3, can you use the .find() method to match a pattern in a string?

A) Yes
B) No
C) It depends

Answer: A. Try this program as an example:

string1 = "abcdefghijklmnopqrstuvwxyz"
number_pattern_found = string1.find("jkl")
print(number_pattern_found)

22. Which of the following is true about Python class names?

A) It is mandatory that a class name's first letter be uppercase.
B) It is mandatory that a class name's first letter be lowercase.
C) It is recommended that a class name's first letter be uppercase.
D) It is recommended that a class name's first letter be lowercase.

Answer: C. Source: https://www.python.org/dev/peps/pep-0008/#class-names

23. What is a way to implement a hash table with Python?

A) a nested list
B) a list of tuples
C) a dictionary
D) a nested dictionary
E) all of the above
F) none of the above

Answer: E.
For A, the source is https://www.geeksforgeeks.org/implementation-of-hashing-with-chaining-in-python/
For B and C, the source is http://blog.chapagain.com.np/hash-table-implementation-in-python-data-structures-algorithms/
This helps explain B:
https://coderbook.com/@marcus/how-to-create-a-hash-table-from-scratch-in-python/
This explains D: https://www.edureka.co/blog/hash-tables-and-hashmaps-in-python/

24. To write your own class in Python, what is necessary? Choose all that apply.

A) The init() function needs to be present.
B) An encapsulated function with the syntax of two leading two underscores __
C) Have an indented block underneath the class definition.
D) Use the class keyword.

Answer: C and D.
The init() function is not strictly necessary. We tested it out. You may want to read this: https://www.w3schools.com/python/python_classes.asp

It is not necessary to use encapsulation. To learn how to use it (but it is optional), see this posting (internal for encapsulation). The creator of this quiz tested that you need more than the class keyword. With nothing underneath a class definition, you may see this error when you try to run the Python program: "IndentationError: expected an indented block". The indented block beneath the class definition can be any (or almost any) valid Python statement. You can run a program such as this (and it will not fail):

class Example:
  a = "nothing"

z = Example()

25. Items in a Python set {} have which of the following traits? Choose all that apply.

A) Unindexed
B) Ordered
C) Immutable
D) Potentially a duplicate of another item in a set

Answer: A and C. The items are not indexed nor changeable. Source for each one: https://www.w3schools.com/python/python_sets.asp

26. Where are variables stored? Choose all that apply.

A) In the heap if they are local variables
B) In the heap if they are global variables
C) In the stack if they are local variables
D) In the stack if they are global variables

Answer: B and C. Source: https://www.geeksforgeeks.org/how-are-variables-stored-in-python-stack-or-heap/

27. Of the following, when should there be space after an equals sign "="?

A) When there is an equivalence test
B) When there is an initialization of an unannotated function parameter
C) When there is a variable assignment involving a reserved word in Python
D) All of the above
E) None of the above

Answer: A. Source: https://www.python.org/dev/peps/pep-0008/#other-recommendations
B and C are instances when there should be no space after the equals sign.

28. There is no difference between an array and a list in Python. True or False?
Answer: False. Source: https://www.geeksforgeeks.org/difference-between-list-and-array-in-python/

29. What is a namedtuple? Choose the best answer.

A. A tuple with a variable name.
B. A tuple that is not indexed by integers but by attribute/key "strings."
C. A tuple that is indexed by integers and has values accessible via attribute/key "strings".
D. None of the above.

Answer: C. Source page 281 of Learning Python by Lutz. To use named tuples you must run a command interactively (or have a line of code) like this: from collections import namedtuple

30. For concurrency to work in multiuser programs, which is less expensive?

A. Multithreading
B. Multiprocessing
C. Using the GIL
D. None of the above.

Answer: A. Source page 509 of Expert Python Programming by Packt Publishing (the 3rd edition). The 4th edition is available here.

31. What does this code return?

def fun_func(n):
  return lambda a : a * n

tripler = fun_func(3)

print(tripler(15))

A. An error about tripler not accepting parameters.
B. An error about fun_func needing an additional parameter
C. 45
D. None of the above.

Answer: C.

32. What does the third line print?

>>> sample_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
>>> new_list = sample_list[:]
>>> new_list

A. []
B. ['a', 'b', 'c', 'd',]
C. ['e', 'f', 'g', 'h']
D. ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']

Answer: D.

33. What does divmod(3, 6) return in Python?

A. 2
B. (0, 2)
C. (2, 0)
D. None of the above

Answer: D. It returns (0, 3)
Source: "The divmod() is part of python’s standard library which takes two numbers as parameters and gives the quotient and remainder of their division as a tuple." (This quote was taken from https://www.tutorialspoint.com/divmod-in-python-and-its-application#.)

34. What does the second line print?

sample_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
sample_list[:2]

A. ['a', 'b']
B. ['h', 'i']
C. ['d', 'e', 'f', 'g', 'h', 'i']
D. None of the above

Answer: A.

35. What does the second line print?

sample_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
sample_list[3:]

A. ['a', 'b']
B. ['a', 'b', 'c']
C. ['d', 'e', 'f', 'g', 'h', 'i']
D. None of the above

Answer: C.

36. What is an f-string in Python? Choose the best answer.

A. A format string specified by an "f" that uses variable substitution with {this_type} of syntax
B. A reserved word in Python for a formatted string
C. A special string variable that is mutable
D. All of the above
E. None of the above.

Answer: A. The "F" can be capitalized or lower case. Source: https://realpython.com/python-f-strings/
The C choice is not that poor of an answer, but it is not the best answer.

37. The isspace method looks for which of the following?

A. One or more spaces
B. Tab characters
C. New lines
D. All of the above
E. None of the above

Answer: D. Source: Page 232 of Python 3 Object-Oriented Programming

38. Which of the following is a class-related method that Python supports?

A. Class
B. Instance
C. Static
D. All of the above
E. None of the above.

Answer: D. Source: Page 1029 of Learning Python by Lutz.

39. What is metaclass in Python?

A. A keyword referring to the __doc__ (aka doc strings) of a class
B. A keyword referring to the attributes of a class
C. Not a keyword, but a concept referring to the "dunder attribute" __attr__
D. None of the above

Answer: D. B could be acceptable. But we think D is the best answer. Source: https://stackoverflow.com/questions/100003/what-are-metaclasses-in-python

40. When are Python decorators executed?

A. Compile time
B. Run time
C. Both of the above
D. None of the above

Answer: B. Source is page 1272 of Learning Python by Lutz.

41. What does MRO stand for?

A. Maintenance Repair Operations
B. Method Resolution Order
C. Metadata Resolve Operate
D. None of the above

Answer: B. Source: https://www.pythonprogramming.in/what-does-mro-do.html

42. What does Enum do in Python?

A. It is a reserved word that creates a list of tuples from 1 until the last number.
B. It is a built-in class whose objects are numbered starting at 1.
C. It is a module that can be imported to facilitate creating objects of a class.
D. None of the above.

Answer: C. Source: https://www.tutorialspoint.com/enum-in-python

43. What is the #! pattern called in Python?
___________________________________

44. What does doc do with a programmer-defined Python object? Choose the best answer.

A. It can display help information from the Python interpreter.
B. It prints the comments of a given object.
C. It prints the comments of a given object (but only those in the top-most comment designated by quotes).
D. None of the above

Answer: C. A. is almost true, but we do not think it is the best answer. Run this code if you want to learn more:

class GoldClass:
    def cool_func():
        """ top line in function """
        # this is a fun test
        """ middle line """
        return "some text"


var_1 = GoldClass.cool_func
print(var_1.__doc__)

45. Consider this code:

import random

neat_list = ["dog", "cat", "hamster"]
random.shuffle(neat_list)

What does random.shuffle(neat_list) do?

A. It does an in-place re-arrangement of the neat_list.
B. It returns a deep copy of a randomized version of neat_list.
C. Both of the above.
D. None of the above.

Answer: A.

46. To read a file you might use something like this:

open('foobar.txt', 'r')

Instead of the "r", what might you use to add text to a file?

A. a
B. w
C. Both of the above
D. None of the above

Answer: C. The "w" stands for write; the "a" stands for append. Write will erase previous content whereas append will not.

47. What does the "\t" signify in Python?

A. It is the syntax to place a given numeric string into a time data type.
B. It is a reference to a tab (e.g., for Python to recognize in a file).
C. It signifies a carriage return (e.g., for printing).
D. This two-character string has no special meaning.

Answer: B. Source: https://stackoverflow.com/questions/22116482/what-does-print-sep-t-mean

48. What does the caret symbol do in the context of a regex statement as follows?

import re
sample = "Very nice"
result = re.search("^Very", sample)

A. The caret symbol finds strings that do not have "Very"
B. The caret symbol finds strings that end with "Very"
C. The caret symbol finds strings that start with "Very"
D. None of the above

Answer: C.

49. What is the difference between a keyword and a built-in?

A. Keywords are part of modules that are imported, but built-ins work without any import statement.
B. Built-ins are part of modules that are imported, but keywords work without any import statement.
C. keywords are set by the user; they are not reserved words.
D. None of the above.

Answer: D. See https://stackoverflow.com/questions/8204542/python3-what-is-the-difference-between-keywords-and-builtins

50. How is index() different from find() in Python?

A. find() returns a Boolean (True or False) while index() returns an integer value
B. find() returns a string while index() returns an integer value
C. when the pattern is not found, they return different things
D. There is no difference.

Answer: C. Source: https://www.programiz.com/python-programming/methods/string/index

find() returns -1 if the pattern is not found and index() returns an error if the pattern is not found.

51. What is a quick way to return the key associated with the dictionary item that is the highest value?

A. max(name_of_dictionary, key=name_of_dictionary.get)
B. max(name_of_dictionary.items())
C. max(name_of_dictionary.values)
D. None of the above

Answer: A.

52. What is the value of int(True) ?

A. 0
B. 1
C. It would produce a command not found error.
D. None of the above.

Answer: B. Successful return codes in Linux are 0. In Python, int(True) is 1. In web applications, they are 2xx.

For more information, see this:
https://askubuntu.com/questions/892604/what-is-the-meaning-of-exit-0-exit-1-and-exit-2-in-a-bash-script
https://www.w3.org/Protocols/HTTP/HTRESP.html

53. How do you create an empty set in Python?

A. Use syntax like this: foobar = {}
B. Use syntax like this: foobar = set()
C. Use syntax like this: foobar = set.empty()
D. None of the above

Answer: B.

54. Complete the following sentence as an answer to the question, how does the Python "any" key word work?

"It accepts an iterable..."

A. and returns a random value from the iterable.
B. and a variable and returns "True" if the variable is in the iterable but it returns False if the variable is not in the iterable.
C. and returns "False" if every element is a zero or an empty string, where a space is considered not empty; otherwise it returns True.
D. and returns "False" if every element is a zero or an empty string, where a space is considered empty; otherwise it returns True.
E. and returns True if any of the variables in the iterable are True but it returns False if every variable is False.
F. and returns the first variable.

Answer: C. We tested it. For more information, see this external posting.

55. What does this code snippet print?

def cool_func(var1, var2):
    sum_vars = var1 + var2 + var3
    return sum_vars

var3 = 100
x = cool_func(2, 7)
print(x)

A. Nothing.
B. "9"
C. "NameError: name 'var3' is not defined"
D. "109"

Answer: D.

56. How is global different from nonlocal?

A. They are functionally equivalent.
B. You need to import sys for nonlocal statements to work.
C. nonlocal applies to functions inside of functions but does not affect variables' values outside of any function. global affects values outside of any function.
D. none of the above.

Answer: C. Source is here.

57. When you are not using Classes in Python, how much of the code relies on modules?

A. 0%
B. Usually about 50%
C. 100%
D. Not enough information to decide; it depends.

Answer: C. Source: Page 745 of Learning Python.

58. What happens when you try to add a duplicate entry to a set in Python?

A. With the .append() syntax or with the .add() syntax the duplicate entry will be added.

B. With the .append() syntax the program will stop processing and an error will show but with the .add() syntax nothing will happen (and the entry won't be added).

C. With the .append() syntax nothing will happen (and the entry won't be added) but with the .add() syntax the program will stop processing and an error will show.

D. Nothing will happen with either .append() syntax or with the .add() syntax, and the duplicate entry will be not added.

Answer: B.

59. How do you add an item to a list in the first position (instead of the last)?

A. appendleft()
B. insert()
C. prepend()
D. create a new temporary list with the item you want and combine it with the original list
E. none of the above
Answer: B. Source: https://www.geeksforgeeks.org/python-perform-append-at-beginning-of-list/

60. What is the difference between a method and a function?

A. There are no functions in Python.
B. There are no methods in Python.
C. Functions are custom-designed whereas methods are built-in.
D. Methods are custom-designed whereas functions are built-in.
E. Methods are associated with classes or objects whereas functions are not.
F. Functions are associated with classes or objects whereas methods are not.

Answer: E. Source is here.

Leave a comment

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