Mixed Deck — All Python Topics Flashcards
99 cards from real Python practice questions. Tap to flip, then mark Knew It or Still Learning — missed cards come back until you master them.
Read the first 20 Mixed Deck — All Python Topics flashcards as text
Which of the following scenarios best demonstrates the concept of polymorphism in Python?
Answer: A function `render_shape(shape)` that can correctly draw a `shape` object whether it is a `Circle` or a `Square`, because both classes have a `.draw()` method.
Polymorphism (from Greek, meaning "many forms") is the ability of an object to take on many forms. In programming, it means that a single interface (like the `render_shape` function) can be used for objects of different types. The function can operate on different shape objects without needing to know their specific type, as long as they adhere to the common interface of having a `.draw()` method.
What is the third argument to file.seek(offset, whence)?
Answer: The reference position: 0=start, 1=current, 2=end
The whence argument specifies the reference point: 0 for start of file, 1 for current position, and 2 for end of file.
Which method removes and returns the last element of a Python list?
Answer: pop()
`list.pop()` removes and returns the last element by default, or an element at a given index.
What does `enumerate()` return when iterating over a list?
Answer: Tuples of (index, value)
`enumerate()` yields `(index, element)` tuples, letting you track both position and value in a loop.
What does the following code output? print(bool(0), bool(3.14159), bool(-3), bool(1.0+1j))
Answer: False True True True
The `bool()` function converts a value to its boolean equivalent. In Python, zero (0), empty sequences/collections, and `None` are considered "falsy". All other numbers (including non-zero integers, floats, and complex numbers) are considered "truthy". Therefore, `bool(0)` is `False`, while `bool(3.14159)`, `bool(-3)`, and `bool(1.0+1j)` are all `True`.
What does the format string `'{0} {1}'.format('Hello', 'World')` produce?
Answer: 'Hello World'
Positional placeholders {0} and {1} are replaced with the first and second format arguments.
Consider the following code snippet. What will be the final content of `inventory`? ```python inventory = {'apples': 10, 'oranges': 5} updates = {'oranges': 15, 'grapes': 20} inventory.update(updates) ```
Answer: {'apples': 10, 'oranges': 15, 'grapes': 20}
The `.update()` method merges the keys and values from one dictionary into another. If a key already exists in the original dictionary, its value is updated with the value from the new dictionary. If a key does not exist, the new key-value pair is added.
What does the walrus operator `:=` do in Python?
Answer: Assigns a value and returns it in the same expression
The walrus operator `:=` (assignment expression) assigns a value to a variable and simultaneously returns that value within an expression.
Which exception is raised when you try to access a list index that is out of range?
Answer: IndexError
`IndexError` is raised when a sequence subscript (index) is out of the valid range.
What does the `global` keyword do inside a Python function?
Answer: Declares that a variable name refers to the module-level global variable
`global x` inside a function tells Python to use and potentially modify the `x` defined at the module level rather than creating a local one.
What is the result of `[str(x) for x in range(3)]`?
Answer: ['0', '1', '2']
str() converts each integer to its string representation, producing ['0', '1', '2'].
What is the output of `bool([])` in Python?
Answer: False
An empty list is falsy in Python, so `bool([])` returns `False`.
Consider the following code. What will be the final output printed to the console? ```python def check_value(): try: print("Start") raise ValueError print("After Raise") except ValueError: print("Caught") return "From Except" finally: print("Cleanup") print("End") print(check_value()) ```
Answer: Start Caught Cleanup From Except
The `try` block starts and prints "Start". A `ValueError` is immediately raised, so "After Raise" is skipped. The `except ValueError` block is executed, printing "Caught". It then prepares to return "From Except". However, the `finally` block must execute before the function officially returns, so "Cleanup" is printed. After the `finally` block completes, the function returns the value from the `except` block, which is then printed. "End" is never reached because the return statement exits the function.
What is the result of `type(lambda: None)`?
Answer:
Lambda expressions create anonymous functions; their type is `function`.
What is a closure in Python?
Answer: A function that captures and remembers variables from its enclosing scope
A closure is an inner function that remembers the values from its enclosing scope even when execution has moved outside that scope.
Which of the following is an invalid variable name in Python?
Answer: 2myVar
Python variable names must start with a letter (a-z, A-Z) or an underscore (_). They cannot begin with a digit. Therefore, '2myVar' is an invalid variable name. '_my_var', 'myVar2', and 'MYVAR' are all valid.
Which expression produces a frozenset?
Answer: frozenset([1, 2, 3])
`frozenset()` accepts an iterable and returns an immutable, hashable set.
What does os.walk() yield for each directory it visits?
Answer: A tuple of (dirpath, dirnames, filenames)
os.walk() yields a 3-tuple (dirpath, dirnames, filenames) for each directory in the tree rooted at the given path.
Which of the following creates a set comprehension?
Answer: {x*2 for x in range(5)}
Curly braces with a single expression and no colon create a set comprehension.
A developer needs to save a Python dictionary to a file so it can be perfectly reconstructed into a dictionary object later. Which module and file mode should be used for this task?
Answer: The `pickle` module with the `'wb'` mode.
The `pickle` module is Python's standard library for serializing and de-serializing Python object structures (a process also called 'pickling'). To save a Python object like a dictionary, you should use `pickle.dump()`. This process requires the file to be opened in binary write mode, which is specified by `'wb'`.
Written and edited by Nathan Beja, founder of Practice Test Geeks, with AI assistance. We have not yet matched this exam's facts to an official source, so confirm fees, dates and rules with the exam body. Editorial policy