Python Python 4 — Questions and Answers
Question 1: What is the difference between `@staticmethod` and `@classmethod` in Python?
- There is no difference
- @staticmethod receives `cls`, @classmethod receives `self`
- @classmethod receives the class as first arg, @staticmethod receives no implicit arg (Correct answer)
- @staticmethod can only be called on instances
Correct answer: @classmethod receives the class as first arg, @staticmethod receives no implicit arg
`@classmethod` receives the class (`cls`) as its first argument, while `@staticmethod` receives no implicit first argument.
Question 2: What will `[x**2 for x in range(5) if x % 2 == 0]` evaluate to?
- [0, 4, 16] (Correct answer)
- [1, 9, 25]
- [0, 1, 4, 9, 16]
- [4, 16]
Correct answer: [0, 4, 16]
The comprehension squares only even numbers from 0–4: 0²=0, 2²=4, 4²=16.
Question 3: Which module provides support for regular expressions in Python?
- regex
- re (Correct answer)
- regexp
- pattern
Correct answer: re
The built-in `re` module provides functions like `re.search()`, `re.match()`, and `re.sub()` for working with regular expressions.
Question 4: What happens when you use `open('file.txt', 'a')` mode?
- Creates a new file or overwrites existing content
- Opens for reading only
- Opens for appending; writes go to end without erasing existing content (Correct answer)
- Opens in binary mode
Correct answer: Opens for appending; writes go to end without erasing existing content
Mode `'a'` opens a file for appending, creating it if it doesn't exist, and all writes go to the end.
Question 5: What does `enumerate()` return when iterating over a list?
- Only the indices
- Only the values
- Tuples of (index, value) (Correct answer)
- A dictionary of index-value pairs
Correct answer: Tuples of (index, value)
`enumerate()` yields `(index, element)` tuples, letting you track both position and value in a loop.
Question 6: Which of the following correctly creates a shallow copy of a list `lst`?
- lst2 = lst
- lst2 = lst.copy() (Correct answer)
- lst2 = deepcopy(lst)
- lst2 = list.clone(lst)
Correct answer: lst2 = lst.copy()
`lst.copy()` creates a new list with the same top-level elements; nested objects are still shared.
Question 7: What exception is raised when you try to access a dictionary key that doesn't exist?
- IndexError
- ValueError
- KeyError (Correct answer)
- AttributeError
Correct answer: KeyError
Accessing a missing dictionary key with bracket notation raises a `KeyError`.
What is the difference between `@staticmethod` and `@classmethod` in Python?