Python289 questions in the bank

Python Quiz: Test Your Python Knowledge

Pick how many questions you want, choose a difficulty and go. You'll see why each answer is right or wrong, then you can retry to beat your score.

Questions
Difficulty
Topic
Mode
  1. Which command checks which version of Python is installed?

    • python -check
    • print(version)
    • python install
    • python --version
  2. What file extension do Python script files use?

    • .pt
    • .pyt
    • .py
    • .python
  3. What does print(10 / 4) show?

    • 2.5
    • 2
    • 2.0
    • 2 remainder 2
  4. What happens if a line starts with an unexpected space?

    • Python ignores the space
    • Python raises an IndentationError
    • The line becomes a comment
    • The line runs twice
  5. Which file extension do Python programs use?

    • .pt
    • .pyt
    • .python
    • .py
  6. What defines a Python statement block?

    • Curly braces
    • Consistent indentation
    • Python ignores the distinction
  7. Which statement correctly describes continuation?

    • Parentheses allow long expressions to continue across physical lines.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  8. What does # inside quoted text represent?

    • A comment marker
    • A character in the string
    • Python ignores the distinction
  9. Which statement correctly describes docstrings?

    • The opening string in a function, class or module documents its public purpose.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  10. Which keyword changes the text between printed arguments?

    • end
    • sep
    • Python ignores the distinction
  11. Which statement correctly describes line endings?

    • end sets the text following the final argument.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  12. What type is the value 3.0?

    • int
    • str
    • float
    • bool
  13. Which variable name follows Python's usual style?

    • total_price
    • TotalPrice
    • totalprice!
    • total-price
  14. What does input() always return?

    • An int
    • Whatever type the user typed
    • A boolean
    • A string
  15. What does print(f"{7 / 2:.1f}") show?

    • 3.5
    • 3
    • 3.50
    • 7 / 2
  16. What does type(int("7") + 0.5) give?

    • <class 'int'>
    • <class 'float'>
    • <class 'str'>
    • An error
  17. What does a = b = [] create?

    • Two independent lists
    • Two references to one list
    • Python ignores the distinction
  18. Which statement correctly describes swapping?

    • The right side is evaluated before its values are assigned to targets.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  19. What does 2 ** 3 equal?

    • 8
    • 6
    • 5
    • 9
  20. What type is the result of 10 / 5?

    • int
    • str
    • bool
    • float
  21. What does round(3.14159, 2) return?

    • 3.14
    • 3.1
    • 3.142
    • 3
  22. Why does 0.1 + 0.2 print 0.30000000000000004?

    • Python has a bug
    • The numbers are strings
    • Some decimals can't be stored exactly in binary
    • round() was missing
  23. What does -7 // 2 give?

    • -3
    • -3.5
    • 3
    • -4
  24. What does int(-3.8) produce?

    • -4
    • -3
    • Python ignores the distinction
  25. Which statement correctly describes truncation?

    • int applied to a finite float discards the fractional part toward zero.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  26. Which test specifically checks for None?

    • not value
    • value is None
    • Python ignores the distinction
  27. Which statement correctly describes implicit results?

    • Functions with no explicit returned value produce None.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  28. What is the index of the first character in a Python string?

    • 1
    • -1
    • It depends on the string
    • 0
  29. Which method removes spaces from both ends of a string?

    • trim()
    • clean()
    • strip()
    • cut()
  30. What does "hello"[::-1] return?

    • "hello"
    • "olleh"
    • "h"
    • An error
  31. Why does s.upper() on its own not change s?

    • upper() only works inside print()
    • Strings are immutable, so upper() returns a new string
    • You must call it twice
    • upper() only changes the first letter
  32. What does "a,b,,c".split(",") return?

    • ['a', 'b', 'c']
    • ['a,b,,c']
    • ['a', 'b', '', 'c']
    • ['a', 'b', ',', 'c']
  33. What does f"{7:03d}" produce?

    • 7
    • 700
    • 007
    • 3d7
  34. Which alignment character centres text?

    • <
    • >
    • =
    • ^
  35. What does "{:>6.1f}".format(3.14159) produce?

    • "3.1 "
    • " 3.1" (right-aligned in 6 characters)
    • "3.14159"
    • " 3.14"
  36. How do you print a literal { inside an f-string?

    • {{
    • \{
    • '{'
    • It isn't possible
  37. Why is it better to format values at the moment you print them?

    • Formatting is slow
    • f-strings can only be used in print()
    • Formatted values are strings, so calculating with them gives wrong results or errors
    • Python forgets formatting after one line
  38. Which type does input return?

    • int
    • str
    • Python ignores the distinction
  39. Which statement correctly describes validation?

    • Conversion checks the representation, and range checks enforce the application rule.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  40. What is bool("0")?

    • False
    • True
    • Python ignores the distinction
  41. Which statement correctly describes truthiness?

    • Zero, empty collections and None are false in conditions.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  42. What does 2 + 3 * 4 evaluate to?

    • 20
    • 14
    • Python ignores the distinction
  43. Which statement correctly describes membership and bits?

    • in checks containment while bitwise operators combine integer bit patterns.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  44. What does == do in Python?

    • Stores a value
    • Checks whether two values are equal
    • Checks whether two values are different
    • Joins two strings
  45. What must come at the end of an if line?

    • A semicolon
    • Curly braces
    • Nothing
    • A colon
  46. How many branches of an if/elif/else chain can run at once?

    • All the true ones
    • Exactly two
    • At most one
    • It depends on the indentation
  47. What is the value of not (5 > 3 and 2 > 4)?

    • True
    • False
    • None
    • An error
  48. What does not (5 > 3) evaluate to?

    • False
    • True
    • 5
    • An error
  49. What does a bare name normally do in a match pattern?

    • Look up an existing constant
    • Capture a value
    • Python ignores the distinction
  50. Which statement correctly describes guards?

    • A case guard checks an additional condition after its pattern succeeds.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  51. Does pass skip the rest of a loop iteration?

    • Yes
    • No
    • Python ignores the distinction
  52. Which statement correctly describes loop behavior?

    • pass does not skip later work in a loop iteration.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  53. Which numbers does range(4) produce?

    • 1, 2, 3, 4
    • 0, 1, 2, 3, 4
    • 0, 1, 2, 3
    • 4
  54. Which loop is best when you don't know how many repeats you need?

    • for
    • range
    • if
    • while
  55. What does break do inside a loop?

    • Exits the loop immediately
    • Pauses the loop for a moment
    • Skips one pass
    • Restarts the loop
  56. How many times does print run here: for i in range(10, 0, -2): print(i)?

    • 4
    • 5
    • 6
    • 10
  57. What does continue do inside a loop?

    • Ends the loop completely
    • Restarts the loop from the beginning
    • Skips the rest of this pass and moves on to the next one
    • Pauses the program
  58. What is the index of the first item in a Python list?

    • 1
    • 0
    • -1
    • It depends on the list
  59. What does len(["x", "y", "z"]) return?

    • 2
    • "xyz"
    • 0
    • 3
  60. What's the difference between my_list.sort() and sorted(my_list)?

    • There is no difference
    • sorted() changes the list itself; sort() returns a new list
    • sort() changes the list itself; sorted() returns a new sorted list
    • sort() only works on numbers
  61. What is ["a", "b", "c", "d", "e"][-2:]?

    • ['d', 'e']
    • ['d']
    • ['c', 'd']
    • ['e']
  62. What's the difference between append and extend?

    • There's none
    • extend adds to the front
    • append sorts the list
    • append adds one item; extend adds every item from another list
  63. Which brackets create a dictionary?

    • { }
    • [ ]
    • ( )
    • < >
  64. What happens when you read a missing key with square brackets?

    • It returns None
    • Python raises a KeyError
    • It returns 0
    • It adds the key
  65. What does d.get("age", 18) return if "age" isn't in d?

    • None
    • 18
    • "age"
    • A KeyError
  66. Which of these can be a dictionary key?

    • A list such as [1, 2]
    • Another dictionary
    • A set
    • A tuple such as (1, 2)
  67. In what order does a loop over a Python 3.7+ dictionary visit the keys?

    • Alphabetical order
    • Random order
    • The order the keys were added
    • Sorted by value
  68. What makes a tuple different from a list?

    • Tuples can only hold numbers
    • Tuples are unordered
    • Tuples can't be changed after they're created
    • Tuples use square brackets
  69. What happens if you add a value that's already in a set?

    • An error
    • It's added twice
    • The old value is replaced
    • Nothing, sets keep only unique values
  70. What does a, b = b, a do?

    • Swaps the values of a and b
    • Raises an error
    • Makes both variables equal to a
    • Creates a list
  71. Which operator gives the items found in both sets?

    • |
    • &
    • -
    • +
  72. Why is ("red") not a tuple?

    • It's the comma that makes a tuple; this is just a string in brackets
    • Tuples can't contain strings
    • Tuples need at least three items
    • It needs square brackets
  73. Which boundary is excluded by range?

    • The start
    • The stop
    • Python ignores the distinction
  74. Which statement correctly describes compact storage?

    • A range stores its defining parameters rather than a list of every generated integer.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  75. What restricts values in array.array?

    • Nothing
    • Its selected type code
    • Python ignores the distinction
  76. Which statement correctly describes sequence operations?

    • Typed arrays support indexing, slices and compatible append operations.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  77. Which operation finds shared set members?

    • Union
    • Intersection
    • Python ignores the distinction
  78. Which statement correctly describes set algebra?

    • Union, intersection, difference and symmetric difference answer different membership questions.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  79. What stays shared after a shallow copy?

    • The new outer container
    • Nested objects
    • Python ignores the distinction
  80. Which statement correctly describes deep copies?

    • deepcopy recursively copies supported structures and tracks previously copied objects.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  81. Which keyword defines a function in Python?

    • function
    • def
    • func
    • define
  82. What does a function return if it has no return statement?

    • 0
    • An empty string
    • None
    • An error
  83. In def area(w, h): and area(3, 4), what are 3 and 4?

    • Parameters
    • Return values
    • Defaults
    • Arguments
  84. What does this print? def f(x): return x * 2 then print(f(f(3)))

    • 12
    • 6
    • 9
    • 36
  85. Which call uses a keyword argument?

    • greet("Ada")
    • greet(name="Ada")
    • greet["Ada"]
    • greet.name("Ada")
  86. What type is args inside def f(*args):?

    • list
    • dict
    • set
    • tuple
  87. What type is kwargs inside def f(**kwargs):?

    • list
    • tuple
    • str
    • dict
  88. What does print(*[1, 2, 3]) print?

    • [1, 2, 3]
    • 1 2 3
    • 123
    • (1, 2, 3)
  89. What happens to a local variable when its function finishes?

    • It disappears
    • It becomes global
    • It's saved for the next call
    • It's printed
  90. What's the safe default for a parameter that should start as an empty list?

    • basket=[]
    • basket=list
    • basket=None, then create a list inside the function
    • basket=()
  91. What terminates recursive descent?

    • A print statement
    • A reachable base case
    • Python ignores the distinction
  92. Which statement correctly describes call stack?

    • Active calls keep separate local state until deeper calls return.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  93. What does a list comprehension return?

    • The original list, changed
    • A new list
    • A string
    • None
  94. In [x for x in items if x > 0], what does the if do?

    • Keeps only items where the condition is true
    • Changes every item
    • Stops the loop
    • Sorts the items
  95. What is a lambda?

    • A loop
    • A small, unnamed function written as one expression
    • A kind of list
    • A module
  96. What does key= do in sorted(items, key=...)?

    • Encrypts the items
    • Removes duplicates
    • Tells sorted() which value to compare for each item
    • Sorts in reverse
  97. What does {w.lower() for w in ["A", "a", "B"]} produce?

    • ['a', 'a', 'b']
    • {'A': 'a', 'B': 'b'}
    • An error
    • {'a', 'b'}
  98. Where should you start reading a traceback?

    • At the top
    • In the middle
    • It doesn't matter
    • At the bottom, which names the error type and message
  99. Which exception does int("hello") raise?

    • TypeError
    • NameError
    • ValueError
    • KeyError
  100. When does a finally block run?

    • Only when there's an error
    • Always
    • Only when there's no error
    • Never inside functions
  101. What does raise ValueError("Too big") do?

    • Stops normal execution with a ValueError carrying that message
    • Prints "Too big" and continues
    • Fixes the value
    • Creates a variable
  102. When does the else block of a try statement run?

    • When an exception is caught
    • Before the try block
    • Only if there's also a finally
    • When the try block finished without any exception
  103. What does with open(...) guarantee?

    • The file exists
    • The file is empty
    • The file is closed when the block ends
    • The file is read-only
  104. What happens if you open an existing file with mode "w"?

    • The file is emptied before writing
    • An error is raised
    • New text is added to the end
    • Nothing changes
  105. Why add encoding="utf-8" when opening text files?

    • It makes files smaller
    • It's required for CSV files only
    • It encrypts the file
    • So characters such as é or ñ are read and written consistently on every system
  106. What type are the values in a row from csv.DictReader?

    • Strings
    • Numbers where possible
    • Lists
    • Booleans
  107. What does the mode "a" do in open("log.txt", "a")?

    • Opens the file read-only
    • Deletes the file first
    • Adds new text to the end, creating the file if needed
    • Opens it as binary
  108. What is a Python module?

    • A type of loop
    • A built-in data type
    • A .py file containing code you can import
    • An error message
  109. What does import pandas as pd do?

    • Imports pandas and lets you refer to it as pd
    • Renames the pandas package on disk
    • Installs pandas
    • Imports only the pd function
  110. What file is commonly used to list a project's packages?

    • packages.py
    • requirements.txt
    • pip.json
    • modules.cfg
  111. Why should you avoid from module import *?

    • It's slower to type
    • It doesn't work in Python 3
    • It only imports classes
    • It imports every name, making it unclear where names come from and risking clashes
  112. What is a virtual environment for?

    • Running Python in the browser
    • Making code run faster
    • Keeping each project's installed packages separate
    • Hiding your code
  113. What does date.today().year give?

    • The current month
    • The date as text
    • The current year as a number
    • The day of the week
  114. What does timedelta(days=7) represent?

    • A specific date
    • A length of time: one week
    • The seventh day of the month
    • Seven o'clock
  115. What does %B show?

    • The short month name
    • The month number
    • The full month name, such as March
    • The weekday
  116. What does strptime raise if the text doesn't match the format?

    • ValueError
    • TypeError
    • KeyError
    • Nothing, it returns None
  117. What does date(2025, 3, 5).weekday() return, given that 5 March 2025 is a Wednesday?

    • 3
    • 4
    • "Wednesday"
    • 2
  118. How do you create an object from a class called Car?

    • new Car()
    • create Car
    • Car.new()
    • Car()
  119. When does __init__ run?

    • Each time a new object is created
    • When the program starts
    • When the object is printed
    • Only once per class
  120. What is a class attribute?

    • An attribute created inside __init__
    • A private attribute
    • An attribute defined in the class body, shared by all instances
    • A method
  121. What does a leading underscore in _balance mean?

    • It's a syntax error
    • By convention, it's internal and should be changed through methods
    • Python makes it read-only
    • It's a class attribute
  122. Why is items = [] in a class body risky for per-object data?

    • Lists can't be attributes
    • It slows the class down
    • The same list is shared by every object of the class
    • It deletes the list each time
  123. What does a subclass inherit from its parent?

    • Nothing
    • Only its __init__
    • Its attributes and methods
    • Only methods named with underscores
  124. What is method overriding?

    • Deleting a parent method
    • Defining a method in the child with the same name as one in the parent
    • Calling a method twice
    • Making a method private
  125. What does super().__init__(name) do inside a child's __init__?

    • Creates a second object
    • Deletes the parent's attributes
    • Calls the child's __init__ again
    • Runs the parent class's __init__ for this object
  126. What is polymorphism?

    • Different classes responding to the same method call in their own way
    • A class with many attributes
    • A class that inherits from many parents
    • Changing an object's type
  127. When is composition usually better than inheritance?

    • When the relationship is "is a"
    • When there are no methods
    • Never
    • When the relationship is "has a"
  128. Which method is intended for diagnostic representation?

    • __str__ only
    • __repr__
    • Python ignores the distinction
  129. Which statement correctly describes diagnostic text?

    • __repr__ helps developers inspect the important state of an object.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  130. Why store _capacity in the property setter?

    • To enforce secrecy
    • To avoid recursive setter calls
    • Python ignores the distinction
  131. Which statement correctly describes static methods?

    • A staticmethod has no automatic self or cls argument.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  132. Does a nested class automatically receive an outer instance?

    • Yes
    • No
    • Python ignores the distinction
  133. Which statement correctly describes composition?

    • An object can contain a collaborator instead of inheriting its behavior.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  134. Does Python stop the program if an argument doesn't match its type hint?

    • No, hints are checked by tools like editors and mypy, not at run time
    • Yes, always
    • Only for ints
    • Only in classes
  135. Which methods does @dataclass generate by default?

    • Only __init__
    • __str__ and __len__
    • All comparison operators
    • __init__, __repr__ and __eq__
  136. How do you give a dataclass field an empty list as its default?

    • items: list = []
    • items: list[str] = list
    • items: list[str] = field(default_factory=list)
    • items: list[str] = None()
  137. What does -> None on a function mean?

    • It returns zero
    • It can't be called
    • It returns an empty string
    • It doesn't return a value
  138. With @dataclass(order=True) and fields major, minor, how are objects compared?

    • Field by field, starting with major, then minor if major is equal
    • By the order they were created
    • By memory address
    • Alphabetically by class name
  139. Which keyword turns a function into a generator?

    • return
    • yield
    • async
    • gen
  140. What does next() raise when an iterator has no more items?

    • IndexError
    • ValueError
    • StopIteration
    • None
  141. What does lazy evaluation mean?

    • Code runs slowly
    • Errors are ignored
    • Values are produced only when they're needed
    • Functions run in the background
  142. What does list(islice(count(5), 3)) give?

    • [0, 1, 2]
    • [5, 5, 5]
    • [3, 4, 5]
    • [5, 6, 7]
  143. What happens to a generator's local variables between next() calls?

    • They're reset
    • They're kept, because the function is paused, not finished
    • They become global
    • They're deleted
  144. What happens to an exhausted iterator in a for loop?

    • It restarts
    • The loop finishes
    • Python ignores the distinction
  145. Which statement correctly describes exhaustion?

    • StopIteration signals that no next value remains.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  146. Where should essential contextmanager cleanup go?

    • Only before yield
    • In finally around yield
    • Python ignores the distinction
  147. Which statement correctly describes bound value?

    • The result of __enter__ is assigned to the name after as.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  148. What is a decorator?

    • A function that takes a function and returns a modified version of it
    • A comment that styles code
    • A type of class
    • A loop
  149. What is a closure?

    • A function with no return
    • An inner function that remembers variables from the function it was defined in
    • The end of a file
    • A closed file object
  150. What does @lru_cache do?

    • Stores results so repeated calls with the same arguments return instantly
    • Deletes old functions
    • Logs every call
    • Limits recursion
  151. How many nested functions does a decorator with arguments normally have?

    • One
    • Two
    • Three
    • Four
  152. When does a decorator run?

    • Every time the program starts a loop
    • Once, when the decorated function is defined; the wrapper runs on each call
    • Only when an error happens
    • Never, it's just a label
  153. Which module provides regular expressions in Python?

    • regex
    • re
    • string
    • pattern
  154. What does ? mean after a character in a pattern?

    • One or more
    • Zero or more
    • Optional: zero or one
    • Exactly one
  155. What does re.search return when nothing matches?

    • An empty string
    • False
    • None
    • An error
  156. What does \s match?

    • A whitespace character
    • The letter s
    • Any symbol
    • The start of the text
  157. In re.sub(r"(\w+) (\w+)", r"\2 \1", "Ada Lovelace"), what's the result?

    • Ada Lovelace
    • \2 \1
    • AdaLovelace
    • Lovelace Ada
  158. What does an automated test do?

    • Runs code with known inputs and checks the result automatically
    • Speeds up the program
    • Formats code
    • Installs packages
  159. In pytest output, what does F mean?

    • Finished
    • A fixture ran
    • A test failed
    • A file was skipped
  160. What is a fixture?

    • A broken test
    • A type of assert
    • A test file
    • A function that prepares data or resources that tests receive as parameters
  161. How do you compare floats safely in a pytest assert?

    • pytest.approx(expected)
    • round both sides to 0 decimals
    • str(a) == str(b)
    • You can't
  162. You've found a bug. What's a good first step?

    • Delete the related tests
    • Write a test that reproduces the bug, then fix the code until it passes
    • Rewrite the whole module
    • Ignore it if other tests pass
  163. What format do most web APIs use for their responses?

    • CSV
    • PDF
    • HTML only
    • JSON
  164. Which HTTP method is normally used to create something new?

    • POST
    • GET
    • HEAD
    • OPTIONS
  165. What does status code 429 tell you?

    • Success
    • The server crashed
    • You're sending too many requests
    • The page moved
  166. Why always pass timeout=?

    • It makes requests faster
    • Without it, a request to a slow server can wait for ever
    • Some APIs require it
    • It retries failed requests
  167. Which exception catches all errors raised by requests, including connection problems?

    • ValueError
    • requests.RequestException
    • HTTPError only
    • KeyError
  168. Which mode refuses to overwrite an existing file?

    • w
    • x
    • Python ignores the distinction
  169. Which statement correctly describes context lifetime?

    • with closes the file when its block ends.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  170. Which function decodes JSON from a string?

    • json.load
    • json.loads
    • Python ignores the distinction
  171. Which statement correctly describes formatting?

    • indent improves readability and ensure_ascii=False preserves readable Unicode characters.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  172. What type is a numeric field returned by DictReader?

    • int
    • str
    • Python ignores the distinction
  173. Which statement correctly describes writing?

    • DictWriter writes named fields using an explicit field order.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  174. Does creating a Path object create a filesystem entry?

    • Yes
    • No
    • Python ignores the distinction
  175. Which statement correctly describes traversal?

    • iterdir lists immediate children while glob can select matching names.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  176. What does ordinary zip do with unequal iterable lengths?

    • Fill missing values automatically
    • Stop at the shortest
    • Python ignores the distinction
  177. Which statement correctly describes transformation?

    • sorted, reversed, enumerate and zip provide useful traversal transformations.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  178. Which method changes a list in place?

    • sorted
    • list.sort
    • Python ignores the distinction
  179. Which statement correctly describes mappings?

    • keys, values and items expose dictionary views and get reads with a fallback.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  180. Which exception normally describes invalid integer text?

    • KeyError
    • ValueError
    • Python ignores the distinction
  181. Which statement correctly describes filesystem errors?

    • FileNotFoundError, PermissionError and other OSError subclasses describe external resource failures.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  182. Is print normally a reserved Python keyword?

    • Yes
    • No
    • Python ignores the distinction
  183. Which statement correctly describes core vocabulary?

    • An argument is a supplied value, a parameter is a declared input and a return value is a produced result.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  184. Which standard library type counts repeated values?

    • Path
    • Counter
    • Python ignores the distinction
  185. Which statement correctly describes collections?

    • Counter counts values, defaultdict supplies missing defaults and deque supports efficient end operations.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  186. What type does os.getenv return when it finds a value?

    • int
    • str
    • Python ignores the distinction
  187. Which statement correctly describes required configuration?

    • Missing required configuration should produce an actionable startup error.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  188. Which form selects pip for a chosen Python interpreter?

    • An unrelated pip executable
    • python -m pip
    • Python ignores the distinction
  189. Which statement correctly describes installation records?

    • A requirements file records dependency specifications for a reproducible setup.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  190. What makes a useful debugging hypothesis?

    • A random code change
    • A prediction you can test
    • Python ignores the distinction
  191. Which statement correctly describes breakpoints?

    • breakpoint enters the configured debugger so execution state can be inspected.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  192. Where does logger.exception normally capture exception context?

    • Before any exception occurs
    • Inside an exception handler
    • Python ignores the distinction
  193. Which statement correctly describes deferred formatting?

    • Passing a format string and arguments defers message interpolation until needed.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  194. Why test an exact capacity boundary?

    • To guarantee every possible input
    • To detect off by one mistakes
    • Python ignores the distinction
  195. Which statement correctly describes parameterization?

    • Parametrized cases check several boundary inputs using one declared test contract.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  196. Where should a dependency usually be patched?

    • Only in its original module
    • Where the tested code looks it up
    • Python ignores the distinction
  197. Which statement correctly describes patching locations?

    • Patch the name used by the code under test rather than guessing its original definition location.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  198. Which style commonly names Python functions?

    • CapWords
    • snake_case
    • Python ignores the distinction
  199. Which statement correctly describes imports and layout?

    • Imports are normally organized near the top and separated into sensible groups.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  200. Do annotations alone enforce parameter types at runtime?

    • Yes
    • No
    • Python ignores the distinction
  201. Which statement correctly describes collection types?

    • Generic annotations describe the element or key and value types inside collections.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  202. What does a loose version constraint guarantee?

    • One exact resolved environment
    • A permitted version range
    • Python ignores the distinction
  203. Which statement correctly describes reproducibility?

    • Record the interpreter, dependency inputs and installation instructions.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  204. Should a project normally commit its .venv directory?

    • Yes
    • No
    • Python ignores the distinction
  205. Which statement correctly describes commits?

    • Focused commits describe one coherent behavior change with a useful message.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  206. Why did editing second also change first?

    • Every list is globally shared
    • Both names reference the same list
    • Python ignores the distinction
  207. Which statement correctly describes problem discussion?

    • Clarify inputs, constraints and expected results before coding.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  208. Does with sqlite3.connect(...) by itself close the connection?

    • Yes
    • No
    • Python ignores the distinction
  209. Which statement correctly describes transactions and closure?

    • Resource closure and transaction handling are related but distinct responsibilities.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  210. Which clause limits rows affected by a simple UPDATE?

    • ORDER BY alone
    • WHERE
    • Python ignores the distinction
  211. Which statement correctly describes value binding?

    • The placeholder syntax belongs to the selected database driver.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  212. How should a member identifier enter a SQL query?

    • By concatenating user text
    • As a bound parameter
    • Python ignores the distinction
  213. Which statement correctly describes parameters?

    • Connector/Python uses parameter placeholders to bind values separately from SQL.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  214. Which update operator changes selected MongoDB fields?

    • Replacing every field manually
    • $set
    • Python ignores the distinction
  215. Which statement correctly describes filters and updates?

    • Query filters select documents while update operators describe requested changes.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  216. Why set a request timeout?

    • To guarantee the server returns valid JSON
    • To bound a wait for network activity
    • Python ignores the distinction
  217. Which statement correctly describes response handling?

    • Status checks and decoding are separate steps.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  218. Can a valid token still lack permission for an operation?

    • No
    • Yes
    • Python ignores the distinction
  219. Which statement correctly describes failure categories?

    • Network failures, error statuses and invalid response data need separate diagnoses.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  220. What type is written to the response body stream?

    • A Python dictionary
    • bytes
    • Python ignores the distinction
  221. Which statement correctly describes encoding?

    • JSON text must be encoded into bytes for a binary response stream.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  222. Should the Flask development debugger be exposed in production?

    • Yes
    • No
    • Python ignores the distinction
  223. Which statement correctly describes request data?

    • JSON and form data arrive through request interfaces and require validation.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  224. What does axis=1 sum in a two dimensional array?

    • Every column into one row
    • Values within each row
    • Python ignores the distinction
  225. Which statement correctly describes axes?

    • Axis arguments select the dimensions along which reductions operate.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  226. Which selector uses integer positions?

    • loc
    • iloc
    • Python ignores the distinction
  227. Which statement correctly describes aggregation?

    • groupby partitions rows into groups before aggregation.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  228. Which object represents an individual plotting area?

    • The filename
    • Axes
    • Python ignores the distinction
  229. Which statement correctly describes labels and scales?

    • Titles, axis labels and appropriate scales help a reader interpret the measurements.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  230. Why retain rejected row information?

    • To increase the reported total
    • To explain cleaning decisions
    • Python ignores the distinction
  231. Which statement correctly describes conversion and provenance?

    • Convert values explicitly and preserve enough information to explain rejected rows.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  232. Which statistic is generally less affected by one extreme duration?

    • Mean
    • Median
    • Python ignores the distinction
  233. Which statement correctly describes sampling?

    • A collected sample may differ from the full process being studied.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  234. Which chart shows the distribution of one numeric variable?

    • Category bar chart
    • Histogram
    • Python ignores the distinction
  235. Which statement correctly describes scatter plots?

    • A scatter plot shows paired numeric observations.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  236. What is the worst case growth of a full list scan?

    • O(1)
    • O(n)
    • Python ignores the distinction
  237. Which statement correctly describes worst and average cases?

    • Different inputs can require different amounts of work.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  238. What prerequisite does binary search require?

    • A random input order
    • A suitably sorted search space
    • Python ignores the distinction
  239. Which statement correctly describes interval invariant?

    • Maintain a search interval that still contains every possible matching position.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  240. What does a stable sort preserve for equal keys?

    • Reverse order
    • Their original relative order
    • Python ignores the distinction
  241. Which statement correctly describes algorithm tradeoffs?

    • Insertion sort illustrates local shifts while merge sort illustrates dividing and combining.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  242. Which order describes a queue?

    • Last in, first out
    • First in, first out
    • Python ignores the distinction
  243. Which statement correctly describes empty structures?

    • Removal from an empty stack or deque needs an explicit policy.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  244. How does a singly linked list reach the next value?

    • By constant time arbitrary indexing
    • By following a next reference
    • Python ignores the distinction
  245. Which statement correctly describes insertion?

    • Insertion can relink a known predecessor without moving a whole array of elements.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  246. Can different dictionary keys have the same hash?

    • No
    • Yes
    • Python ignores the distinction
  247. Which statement correctly describes hashable keys?

    • A key needs a stable hash and a compatible equality contract while stored.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  248. What determines search cost in a simple BST?

    • Only the root value
    • The tree height
    • Python ignores the distinction
  249. Which statement correctly describes traversal?

    • Inorder, preorder and postorder visit the same structure in different sequences.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  250. Which traversal finds shortest hop counts in an unweighted graph?

    • Any depth first traversal
    • Breadth first search
    • Python ignores the distinction
  251. Which statement correctly describes breadth first search?

    • BFS explores by distance in edge count using a queue.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  252. What must mutable backtracking restore?

    • Every global variable
    • The state changed for the current choice
    • Python ignores the distinction
  253. Which statement correctly describes memoization?

    • Caching results can avoid solving an identical subproblem repeatedly.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  254. Why compare a learned model with a baseline?

    • To avoid all evaluation
    • To check whether complexity improves useful performance
    • Python ignores the distinction
  255. Which statement correctly describes baselines?

    • A simple baseline gives a model result a useful comparison.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  256. What does multimode help represent?

    • Only the arithmetic average
    • Ties among most frequent values
    • Python ignores the distinction
  257. Which statement correctly describes standard deviation?

    • Standard deviation expresses spread in the original measurement units.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  258. Why can percentile calculations differ between tools?

    • Percentiles are unrelated to ordering
    • They can use different interpolation conventions
    • Python ignores the distinction
  259. Which statement correctly describes outlier meaning?

    • An unusual observation may be an error or an important real event.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  260. What kind of target does ordinary linear regression predict?

    • Only a category label
    • A numeric value
    • Python ignores the distinction
  261. Which statement correctly describes fitting and residuals?

    • Fitting selects coefficients according to an objective, and residuals compare observed with predicted outcomes.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  262. What does predict_proba provide?

    • Guaranteed outcomes
    • Estimated class probabilities
    • Python ignores the distinction
  263. Which statement correctly describes decision thresholds?

    • A threshold turns a probability into a decision and should reflect the task tradeoffs.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  264. Why scale mixed KNN features?

    • To guarantee perfect accuracy
    • Because distance depends on their magnitudes
    • Python ignores the distinction
  265. Which statement correctly describes hyperparameters?

    • Tree depth and neighbor count are choices selected using training side validation.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  266. Which observations should fit a preprocessing transformation?

    • The full dataset including test observations
    • Training observations
    • Python ignores the distinction
  267. Which statement correctly describes preprocessing?

    • Learn transformations on training observations and apply the learned transformation to held out data.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  268. Why include preprocessing inside the cross validation pipeline?

    • To inspect the final test target
    • To fit it separately on each training fold
    • Python ignores the distinction
  269. Which statement correctly describes metrics?

    • A metric should match the outcome and operational consequences.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  270. Do K-means cluster labels have inherent category meanings?

    • Yes
    • No
    • Python ignores the distinction
  271. Which statement correctly describes scaling and choices?

    • Feature scale, cluster count and initialization affect the result.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  272. What should you identify before adapting an example?

    • Only its line count
    • Its inputs, outputs and assumptions
    • Python ignores the distinction
  273. Which statement correctly describes variation?

    • Changing one meaningful assumption tests whether the underlying idea is understood.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  274. What should a challenge include besides an ordinary example?

    • Only a time limit
    • Boundary and adversarial cases
    • Python ignores the distinction
  275. Which statement correctly describes incremental solutions?

    • A clear working approach can be improved after its behavior is verified.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  276. Why attempt a problem before reading its solution?

    • To guarantee a perfect first answer
    • To expose your current reasoning and gaps
    • Python ignores the distinction
  277. Which statement correctly describes delayed solutions?

    • Attempt the task and record a prediction before comparing a worked solution.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  278. What makes an advanced exercise valuable?

    • Only a larger line count
    • Design and tradeoff decisions with evidence
    • Python ignores the distinction
  279. Which statement correctly describes advanced exercises?

    • Advanced tasks ask for design, testing and performance decisions rather than merely longer syntax.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  280. How should a missed quiz question guide study?

    • Memorize the option position
    • Review its explanation and apply the concept again
    • Python ignores the distinction
  281. Which statement correctly describes error analysis?

    • A wrong answer is useful when its explanation identifies the mistaken rule.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  282. What should the first project milestone provide?

    • Every planned feature at once
    • One small working behavior
    • Python ignores the distinction
  283. Which statement correctly describes milestones?

    • Deliver one working behavior at a time with observable examples.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  284. Which responsibility should be separated from stock arithmetic?

    • The meaning of subtraction
    • External file parsing
    • Python ignores the distinction
  285. Which statement correctly describes testing collaborators?

    • Test pure logic directly and control external file dependencies with temporary data.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  286. Do adjacent half open booking intervals overlap?

    • Yes
    • No
    • Python ignores the distinction
  287. Which statement correctly describes performance evidence?

    • Measure a representative workload before choosing an optimization.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
  288. When should the separate machine learning track be approached?

    • Before variables and collections
    • After the core and relevant data science prerequisites
    • Python ignores the distinction
  289. Which statement correctly describes optional tracks?

    • Database and web, data science, DSA and machine learning are goal dependent branches.
    • Only the example output matters, not the rule
    • Every operation has the same behavior
RelaxedNo clock. Read the explanation after each answer.
Timed30 seconds per question. Great for revision.
Exam modeNo feedback until the end, then a full review.

About the Python quiz

This Python quiz checks the ideas from every lesson in the course, from print() and variables to decorators, regular expressions and testing. Most questions show a few lines of code and ask what they print, because reading code and predicting its output is the single most useful skill when you're learning to program. Others check vocabulary such as "parameter", "immutable" or "exception", which you'll need when reading documentation and error messages.

If you're still in the beginner stage, choose Easy and pick a topic you've just finished, such as strings or loops. Once you've worked through the intermediate lessons, try Mixed with 10 questions: you'll meet lists, dictionaries and functions side by side, just as they appear in real programs. Save Exam mode for when you've finished the course; it hides the answers until the end, so it's an honest check of what you remember.

When you get a question wrong, read the explanation, then open the lesson linked in your results and look at its examples again. Mistakes in Python often come from small details: an index that starts at 0, a method that returns a new string instead of changing the old one, or an indent in the wrong place. Spotting those details in a quiz is exactly what makes them easy to avoid in your own code.

The question bank holds 289 questions drawn from 107 Python lessons: 119 easy, 144 medium and 26 hard. Every time you start, the quiz picks a fresh random selection that matches your settings, so retaking it is a good way to practise. After each answer, or at the end in exam mode, you'll see why the right answer is right, and every question you miss links back to the lesson that teaches it.

What the Python quiz covers