




























































































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
This practice exam evaluates expert-level Python proficiency, covering OOP, decorators, generators, advanced collections, multithreading and multiprocessing, asynchronous programming (async/await), API development with Flask/Django, data structures, and debugging. The exam challenges candidates with algorithmic problems, performance optimization tasks, and real-world application scenarios.
Typology: Exams
1 / 128
This page cannot be seen from the preview
Don't miss anything!





























































































Question 1. Which built‑in decorator is used to preserve a wrapped function’s metadata such as its name and docstring? A) @staticmethod B) @property C) @functools.wraps D) @lru_cache Answer: C Explanation: functools.wraps copies the original function’s name, doc, and other attributes to the wrapper. Question 2. In a decorator that accepts arguments, which of the following must be the outermost function? A) The function that receives *args and **kwargs. B) The function that returns the wrapper. C) The function that receives the decorator arguments. D) The original function being decorated. Answer: C Explanation: When a decorator takes arguments, the first (outer) function receives those arguments and returns the actual decorator. Question 3. What does the following code print?
def outer(): x = 5 def inner(): return x ## Python Practice Exam return inner f = outer() print(f()) A) 0 B) 5 C) NameError D) None Answer: B Explanation: inner forms a closure over x, retaining its value (5) after outer() returns. Question 4. Which of the following statements about new and init is true? A) new creates the instance; init initializes it. B) init creates the instance; new initializes it. C) Both are called only for immutable types. D) new is optional but init is mandatory. Answer: A Explanation: new is a static method that actually creates the object; init then sets up its state. Question 5. When implementing a custom iterator, which methods must be defined? A) iter only B) next only C) iter and next D) getitem and len
C) Metaclasses cannot modify class attributes. D) Metaclasses are only available in Python 2. Answer: B Explanation: All new‑style classes are created by the built‑in metaclass type. Question 9. In the context of attribute access, what does overriding __getattr__ allow you to do? A) Intercept all attribute reads, even those that exist. B) Provide a fallback for attributes that are not found in the usual places. C) Change the way attributes are stored on the object. D) Prevent attribute deletion. Answer: B Explanation: __getattr__ is only called when normal attribute lookup fails. Question 10. Which of the following is a correct way to create a context manager using contextlib.contextmanager? A)
@contextmanager def cm(): yield B)
class cm: ## Python Practice Exam def __enter__(self): pass def __exit__(self, *exc): pass C) Both A and B are correct. D) Neither A nor B are correct. Answer: A Explanation: The decorator transforms a generator function into a context manager; option B is a manual implementation. Question 11. What is the time complexity of checking membership (x in s) for a Python set with n elements? A) O(1) average, O(n) worst‑case B) O(log n) C) O(n) D) O(n log n) Answer: A Explanation: Sets are hash tables; look‑ups are constant‑time on average, though collisions can degrade to linear. Question 12. Which collections class maintains insertion order and also allows duplicate keys? A) defaultdict B) Counter C) OrderedDict D) ChainMap Answer: C
Explanation: deque is optimized for O(1) appends and pops on both ends; insert and sort are not O(1). Question 16. Which of the following list comprehensions produces the same list as list(map(str, range(5)))? A) [str(i) for i in range(5)] B) [i for i in range(5) if isinstance(i, str)] C) [str(i) for i in range(5) if i%2==0] D) [str(i) for i in range(1,5)] Answer: A Explanation: Both generate string representations of numbers 0‑4. Question 17. What does the reduce function from functools do? A) Filters elements based on a predicate. B) Applies a binary function cumulatively to the items of an iterable, reducing it to a single value. C) Maps each element to a new value. D) Returns an iterator that yields cumulative sums. Answer: B Explanation: reduce folds the iterable using the provided binary function. Question 18. Which of the following is a risk when using pickle for object serialization? A) It cannot serialize custom classes. B) It is platform‑independent. C) Unpickling data from an untrusted source can execute arbitrary code. D) It always produces human‑readable output.
Answer: C Explanation: Pickle is not safe against malicious data because it can invoke any callable during unpickling. Question 19. In Python, what is the purpose of the __slots__ attribute in a class definition? A) To declare static methods. B) To restrict attribute creation to a fixed set, reducing memory overhead. C) To enable multiple inheritance. D) To automatically generate __init__. Answer: B Explanation: __slots__ tells the interpreter to allocate a static structure for attributes, eliminating per‑instance __dict__. Question 20. Which statement about @classmethod is true? A) It receives the instance as the first argument. B) It can be called on the class without creating an instance. C) It cannot access class variables. D) It is equivalent to a static method. Answer: B Explanation: A classmethod receives the class (cls) as its first argument and can be invoked directly on the class. Question 21. What is the Method Resolution Order (MRO) used for in Python? A) To determine the order of execution of finally blocks. B) To decide which base class’s method is called in multiple inheritance.
Question 24. When defining a custom class that should be usable as a dictionary key, which method(s) must be implemented? A) __hash__ only B) __eq__ only C) Both __hash__ and __eq__ D) __cmp__ Answer: C Explanation: Objects used as dict keys must be hashable (__hash__) and comparable for equality (__eq__). Question 25. Which design pattern ensures that a class has only one instance throughout a program? A) Factory B) Observer C) Singleton D) Strategy Answer: C Explanation: The Singleton pattern restricts instantiation to a single object. Question 26. In the Observer pattern, which component receives notifications when the subject’s state changes? A) Subject B) Observer C) Factory D) Mediator Answer: B
Explanation: Observers register with a subject and are notified of state changes. Question 27. Which of the following statements about the Global Interpreter Lock (GIL) is correct? A) It allows multiple native threads to execute Python bytecode simultaneously. B) It prevents any form of concurrency in Python. C) It only affects CPU‑bound threads, not I/O‑bound ones. D) It is removed in Python 3.10. Answer: C Explanation: The GIL serializes execution of Python bytecode, limiting CPU‑bound multithreading but I/O‑bound threads can still run while waiting. Question 28. Which module provides a high‑level interface for creating a pool of worker processes? A) threading B) multiprocessing C) asyncio D) concurrent.futures (process executor) Answer: B Explanation: multiprocessing.Pool creates a pool of processes for parallel execution. Question 29. What does the async keyword indicate when defining a function? A) The function runs in a separate OS thread. B) The function returns a coroutine object that must be awaited. C) The function is automatically executed in parallel. D) The function cannot contain await.
D) percall Answer: A Explanation: tottime is the total time spent in the function itself; cumtime includes sub‑calls. Question 33. Which of the following statements about Python’s garbage collector is true? A) It only works for objects with a __del__ method. B) It can detect and collect cyclic references. C) It immediately frees memory as soon as reference count drops to zero. D) It cannot be disabled. Answer: B Explanation: The cyclic GC runs periodically to break reference cycles that reference counting alone cannot reclaim. Question 34. Which of the following is the most appropriate way to create a virtual environment named env using the standard library? A) python - m venv env B) virtualenv env C) conda create - n env python D) pipenv --python env Answer: A Explanation: python - m venv creates a lightweight virtual environment in the specified directory. Question 35. In unittest, which method is called before each test method is executed? A) setUpClass
B) tearDown C) setUp D) __init__ Answer: C Explanation: setUp runs before every individual test method; setUpClass runs once per test class. Question 36. Which logging level has the highest numeric value (i.e., the most severe)? A) DEBUG B) INFO C) WARNING D) CRITICAL Answer: D Explanation: Logging levels increase in severity: DEBUG < INFO < WARNING < ERROR < CRITICAL. Question 37. Which of the following is a secure way to store a password hash in a Python application? A) Use hashlib.sha1 directly on the password. B) Store the plaintext password in an environment variable. C) Use bcrypt or argon2 with a salt. D) Encode the password with base64. Answer: C Explanation: Modern password‑hashing algorithms like bcrypt/argon2 incorporate salts and work factors, making them resistant to brute‑force attacks.
Question 41. Which of the following SQLAlchemy patterns is used to ensure that a session is automatically rolled back on exception? A) session.begin() B) with session.begin(): C) session.commit() D) session.flush() Answer: B Explanation: The context manager session.begin() provides transactional scope with automatic rollback on errors. Question 42. In MongoDB’s pymongo, which method inserts a single document into a collection? A) insert_one B) add C) save D) push Answer: A Explanation: collection.insert_one(document) inserts one document and returns an InsertOneResult. Question 43. Which of the following socket types provides a reliable, connection‑oriented byte stream? A) SOCK_DGRAM B) SOCK_RAW C) SOCK_STREAM
SOCK_SEQPACKETAnswer: C Explanation: SOCK_STREAM (TCP) ensures ordered, reliable delivery. Question 44. Which BeautifulSoup parser is the fastest but may not handle malformed HTML as well? A) html.parser B) lxml C) html5lib D) xml Answer: B Explanation: lxml is written in C and offers speed; html5lib is more tolerant but slower. Question 45. What is the worst‑case time complexity of searching for an element in a balanced binary search tree (BST) with n nodes? A) O(1) B) O(log n) C) O(n) D) O(n log n) Answer: B Explanation: A balanced BST has height log n, so lookup follows a path of that length. Question 46. Which sorting algorithm has the best average‑case time complexity for general-purpose sorting in CPython? A) Quick sort B) Merge sort
def fact(n): return reduce(lambda x, y: x*y, range(1, n+1)) Answer: B Explanation: Option B includes the base case (n == 0) to stop recursion. Question 48. Which itertools function generates the Cartesian product of input iterables? A) permutations B) combinations C) product D) chain Answer: C Explanation: itertools.product(*iterables) yields the Cartesian product. Question 49. Which of the following statements about Python’s asyncio.Queue is true? A) It blocks the event loop when get() is called on an empty queue. B) It is thread‑safe but not coroutine‑safe. C) put_nowait raises QueueFull if the queue is full. D) It cannot be used with await. Answer: C Explanation: put_nowait raises QueueFull immediately if the maxsize is reached.
Question 50. In a dataclass, which parameter disables the generation of the __init__ method? A) init=False B) repr=False C) eq=False D) order=False Answer: A Explanation: @dataclass(init=False) tells the decorator not to create an __init__. Question 51. Which of the following best describes the purpose of the __dir__ method? A) To customize attribute deletion. B) To provide a list of attribute names for dir() and IDE autocomplete. C) To intercept attribute assignment. D) To define the iterator protocol. Answer: B Explanation: __dir__ returns a list of attribute names that dir() uses. Question 52. Which of the following statements about functools.partial is correct? A) It creates a new function that always returns the same value. B) It binds some arguments of a callable, returning a new callable with fewer parameters. C) It memoizes the original function. D) It decorates a function to log its calls. Answer: B Explanation: partial pre‑sets positional or keyword arguments.