Python quiz

Syntax, data types, loops, functions and the standard library.

94 questionsInstant feedbackFree

Set up your quiz

Difficulty
Number of questions

Tip: press 1–4 to answer and Enter for the next question.

All 94 questions with answers
  1. Which keyword is used to define a function in Python?

    • define
    • fun
    • def (correct)
    • function
  2. What is the output of print(type([]))?

    • <class 'tuple'>
    • <class 'dict'>
    • <class 'str'>
    • <class 'list'> (correct)
  3. Which of the following data types is immutable?

    • list
    • dict
    • tuple (correct)
    • set
  4. What does len("Python") return?

    • 5
    • 6 (correct)
    • 7
    • Error
  5. Which symbol is used for single-line comments in Python?

    • //
    • /* */
    • --
    • # (correct)
  6. What is the output of 7 // 2?

    • 3.5
    • 4
    • 3 (correct)
    • 3.0
  7. What is the output of 2 ** 3?

    • 6
    • 8 (correct)
    • 9
    • 5
  8. Which method adds an item to the end of a list?

    • append() (correct)
    • add()
    • push()
    • insert_end()
  9. Which of the following creates an empty dictionary?

    • []
    • ()
    • {} (correct)
    • dict[]
  10. What is the output of bool("")?

    • True
    • False (correct)
    • None
    • Error
  11. Which keyword is used to handle exceptions in Python?

    • catch
    • handle
    • except (correct)
    • rescue
  12. What sequence does range(5) generate?

    • 0, 1, 2, 3, 4 (correct)
    • 1, 2, 3, 4, 5
    • 0, 1, 2, 3, 4, 5
    • 1, 2, 3, 4
  13. What is the output of "abc".upper()?

    • abc
    • Abc
    • ABC (correct)
    • Error
  14. Which function is used to read input from the user?

    • scanf()
    • read()
    • get()
    • input() (correct)
  15. What is the output of 10 % 3?

    • 0
    • 3
    • 1 (correct)
    • 3.33
  16. What does [x * 2 for x in range(3)] return?

    • [0, 2, 4] (correct)
    • [2, 4, 6]
    • [0, 1, 2]
    • [0, 2, 4, 6]
  17. Which keyword is used to create a class in Python?

    • struct
    • object
    • define
    • class (correct)
  18. What is the purpose of the __init__ method in a class?

    • It destroys the object
    • It initializes a new object (constructor) (correct)
    • It imports a module
    • It defines a static method
  19. What is the output of print("Hi" * 3)?

    • Hi3
    • Error
    • HiHiHi (correct)
    • Hi Hi Hi
  20. Which statement skips the rest of the current loop iteration?

    • break
    • pass
    • continue (correct)
    • exit
  21. Which is the correct way to import the math module?

    • include math
    • using math
    • import math (correct)
    • #import math
  22. What is the output of type(3 / 2)?

    • <class 'int'>
    • <class 'float'> (correct)
    • <class 'double'>
    • <class 'decimal'>
  23. What does the pass statement do?

    • Does nothing (acts as a placeholder) (correct)
    • Exits the program
    • Skips the loop iteration
    • Raises an error
  24. What is the output of len({1, 2, 2, 3})?

    • 4
    • 3 (correct)
    • 2
    • Error
  25. What is the output of [1, 2, 3][-1]?

    • 1
    • Error
    • 2
    • 3 (correct)
  26. Which keyword is used to create an anonymous function?

    • lambda (correct)
    • anon
    • func
    • def
  27. Which string method removes whitespace from both ends?

    • strip() (correct)
    • trim()
    • clean()
    • cut()
  28. What does *args do in a function definition?

    • Passes keyword arguments
    • Accepts any number of positional arguments (correct)
    • Unpacks a dictionary
    • Multiplies all arguments
  29. What is the output of: a = [1, 2, 3]; b = a; b.append(4); print(a)?

    • [1, 2, 3]
    • [1, 2, 3, 4] (correct)
    • Error
    • [4]
  30. What is a decorator in Python?

    • A comment style
    • A type of loop
    • A class attribute
    • A function that modifies the behavior of another function (correct)
  31. Which statement about the GIL in CPython is true?

    • It allows unlimited threads to run Python bytecode in parallel
    • It only affects Python 2
    • It lets only one thread execute Python bytecode at a time (correct)
    • It speeds up multiprocessing
  32. What is the difference between == and is?

    • == compares identity, is compares values
    • They are identical
    • == compares values, is compares object identity (correct)
    • is only works with numbers
  33. What does the yield keyword do?

    • Ends the program
    • Defines a class
    • Imports a module
    • Turns a function into a generator (correct)
  34. What is the output of print(0.1 + 0.2 == 0.3)?

    • True
    • False (correct)
    • Error
    • None
  35. Given def f(x, l=[]): l.append(x); return l — what does f(1); print(f(2)) output?

    • [2]
    • [1]
    • [1, 2] (correct)
    • Error
  36. Which function returns the number of items in a list?

    • size()
    • count()
    • length()
    • len() (correct)
  37. Which data type is created by writing (1, 2, 3)?

    • dict
    • set
    • tuple (correct)
    • list
  38. Which data type is created by writing {1, 2, 3}?

    • dict
    • set (correct)
    • tuple
    • list
  39. What does print(10 / 2) display in Python 3?

    • 5
    • Error
    • 5.00
    • 5.0 (correct)
  40. Which keyword is used for a conditional branch after if?

    • elseif
    • else if
    • elif (correct)
    • ifelse
  41. What does the str() function do?

    • Converts a value to a string (correct)
    • Checks a string
    • Reverses a string
    • Splits a string
  42. What does int("42") return?

    • 42.0
    • "42"
    • Error
    • 42 (correct)
  43. How do you start a for loop over the numbers 0 to 4?

    • for i to 5:
    • for i in range(5): (correct)
    • foreach i in 5:
    • for (i = 0; i < 5; i++):
  44. Which operator checks if a value is in a list?

    • in (correct)
    • exists
    • contains
    • has
  45. What does "hello"[0] return?

    • 'o'
    • 'h' (correct)
    • 'hello'
    • Error
  46. Which method splits a string into a list of words?

    • cut()
    • divide()
    • split() (correct)
    • words()
  47. What is the output of print(3 > 2 and 2 > 5)?

    • Error
    • False (correct)
    • None
    • True
  48. Which built-in function returns the largest item?

    • big()
    • max() (correct)
    • largest()
    • top()
  49. What does abs(-7) return?

    • -7
    • Error
    • 0
    • 7 (correct)
  50. Which keyword returns a value from a function?

    • return (correct)
    • give
    • output
    • yield only
  51. Which method removes and returns the last item of a list?

    • cut()
    • pop() (correct)
    • delete()
    • remove()
  52. What does round(3.7) return?

    • 4 (correct)
    • 3.7
    • 4.0
    • 3
  53. Which loop keeps running while a condition is true?

    • repeat
    • while (correct)
    • for
    • do
  54. What does "a,b,c".split(",") return?

    • ['a,b,c']
    • ['a', 'b', 'c'] (correct)
    • 'abc'
    • ('a', 'b', 'c')
  55. What does ", ".join(["a", "b"]) return?

    • 'ab'
    • 'a, b' (correct)
    • 'a b'
    • ['a', 'b']
  56. What is the output of "Python"[1:4]?

    • 'yth' (correct)
    • 'pyth'
    • 'Pyt'
    • 'ytho'
  57. What is the output of "Python"[::-1]?

    • Error
    • 'P'
    • 'nohtyP' (correct)
    • 'Python'
  58. What does dict.get("key", 0) do if the key is missing?

    • Raises KeyError
    • Returns None always
    • Returns 0 (correct)
    • Adds the key with value 0
  59. Which method returns all key-value pairs of a dictionary?

    • entries()
    • all()
    • pairs()
    • items() (correct)
  60. What does enumerate(["a", "b"]) give you in a loop?

    • Index and value pairs (correct)
    • Only the values
    • A dictionary
    • Only the indexes
  61. What does zip([1, 2], ["a", "b"]) produce when turned into a list?

    • [[1, 2], ['a', 'b']]
    • [(1, 'a'), (2, 'b')] (correct)
    • {1: 'a', 2: 'b'}
    • [1, 2, 'a', 'b']
  62. What does {x: x * x for x in range(3)} create?

    • (0, 1, 4)
    • [0, 1, 4]
    • {0, 1, 4}
    • {0: 0, 1: 1, 2: 4} (correct)
  63. What does **kwargs collect in a function?

    • Extra positional arguments as a tuple
    • Only required arguments
    • Global variables
    • Extra keyword arguments as a dictionary (correct)
  64. Which statement opens a file and closes it automatically?

    • open("f.txt").auto()
    • with open("f.txt") as f: (correct)
    • f = open("f.txt", close=True)
    • file("f.txt")
  65. Which file mode opens a file for appending?

    • "x"
    • "w"
    • "a" (correct)
    • "r"
  66. What happens when you open an existing file with mode "w"?

    • It opens read-only
    • Its contents are erased first (correct)
    • New text is added to the end
    • An error is raised
  67. Which exception is raised when converting int("abc")?

    • KeyError
    • TypeError
    • IndexError
    • ValueError (correct)
  68. Which exception is raised by accessing a missing dictionary key with d["x"]?

    • NameError
    • KeyError (correct)
    • IndexError
    • ValueError
  69. What does sorted([3, 1, 2]) return?

    • [3, 2, 1]
    • [1, 2, 3] as a new list (correct)
    • It sorts in place and returns the list
    • None
  70. What does list.sort() return?

    • None (correct)
    • A copy of the list
    • The sorted list
    • True
  71. What does the global keyword do inside a function?

    • Creates a constant
    • Makes the function public
    • Lets the function assign to a module-level variable (correct)
    • Imports a module
  72. What does if __name__ == "__main__": check?

    • Whether the file is being run directly rather than imported (correct)
    • Whether Python is installed
    • Whether the file is the first in a folder
    • Whether the function is called main
  73. Which module provides random numbers?

    • rand
    • numbers
    • math
    • random (correct)
  74. What does any([False, True, False]) return?

    • [True]
    • True (correct)
    • False
    • 1
  75. What does all([]) return?

    • True (correct)
    • False
    • None
    • Error
  76. Which method adds all items from another list to the end of a list?

    • add()
    • extend() (correct)
    • append()
    • insert()
  77. What is the output of [1, 2] + [3]?

    • [4, 2]
    • Error
    • [1, 2, 3] (correct)
    • [1, 2, [3]]
  78. What does a generator expression like (x * 2 for x in range(3)) return?

    • A set
    • A generator object that produces values lazily (correct)
    • A list
    • A tuple
  79. What is a shallow copy of a list?

    • A new list whose elements still reference the same objects (correct)
    • A list with half the elements
    • A copy of every nested object
    • A pointer to the same list
  80. Which function makes a deep copy of a nested structure?

    • dict()
    • list.copy()
    • copy.copy()
    • copy.deepcopy() (correct)
  81. What does @staticmethod mean?

    • The method is private
    • The method cannot change
    • The method takes neither self nor cls (correct)
    • The method runs once
  82. What does @classmethod receive as its first argument?

    • Nothing
    • The instance (self)
    • The module
    • The class (cls) (correct)
  83. What does @property do?

    • Caches the result forever
    • Makes an attribute private
    • Lets a method be accessed like an attribute (correct)
    • Makes a method static
  84. What is the MRO in Python?

    • The main run order
    • The order in which classes are searched for a method in inheritance (correct)
    • The memory release order
    • The module reload order
  85. What do the dunder methods __enter__ and __exit__ implement?

    • String conversion
    • The context manager protocol used by with (correct)
    • Iteration
    • Comparison
  86. Which method makes an object usable in a for loop?

    • __len__
    • __call__
    • __iter__ (correct)
    • __str__
  87. What does functools.lru_cache do?

    • Caches function results for repeated arguments (correct)
    • Sorts function arguments
    • Logs function calls
    • Limits recursion depth
  88. What is the output of print([i for i in range(10) if i % 3 == 0])?

    • [1, 4, 7]
    • [0, 3, 6]
    • [3, 6, 9]
    • [0, 3, 6, 9] (correct)
  89. What does the walrus operator := do?

    • Swaps two variables
    • Assigns a value as part of an expression (correct)
    • Declares a constant
    • Compares two values
  90. Which statement about Python dictionaries in 3.7+ is true?

    • They preserve insertion order (correct)
    • They are sorted by key
    • They allow duplicate keys
    • They are immutable
  91. What does asyncio mainly help with?

    • Compiling Python
    • Speeding up CPU-heavy math
    • Running many IO-bound tasks concurrently in one thread (correct)
    • Multiprocessing
  92. What is the output of print(type(lambda: 0))?

    • <class 'lambda'>
    • <class 'callable'>
    • <class 'method'>
    • <class 'function'> (correct)
  93. Which module is used to work with regular expressions?

    • string
    • re (correct)
    • rx
    • regex
  94. What do *a, b = [1, 2, 3] assign to a?

    • 1
    • [1, 2] (correct)
    • [1, 2, 3]
    • (1, 2)