




















































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
The Certified Associate in Python Programming PCAP Ultimate Exam provides comprehensive preparation for individuals seeking to validate their Python programming skills. The exam covers variables, data types, control structures, functions, object-oriented programming, modules, exceptions, file handling, and Python development best practices. It is ideal for aspiring programmers, software developers, and IT professionals looking to strengthen their coding abilities and prepare for industry-recognized Python certification.
Typology: Exams
1 / 60
This page cannot be seen from the preview
Don't miss anything!





















































Question 1. Which of the following statements correctly describes a Python module? A) A module is a compiled binary file that cannot be edited. B) A module is a .py source file that defines functions, classes, and variables. C) A module is a special type of dictionary used for configuration. D) A module is an interpreter setting that controls memory usage. Answer: B Explanation: In Python, a module is a plain text file with a .py extension that contains definitions of functions, classes, variables, and runnable code. It can be imported by other modules. Question 2. When Python executes import mypkg.mymodule, which attribute of the imported module indicates the name of the file that was executed as the entry point? A) __file__ B) __name__ C) __package__ D) __path__ Answer: B Explanation: __name__ holds the module’s fully qualified name. When a module is run as a script, its __name__ becomes "__main__"; otherwise it reflects the import path. **Question 3. What does the following code print?
import sys print('src' in sys.path)A) True if the current directory contains a folder named src. B) True if the string 'src' appears anywhere in the list of directories.
C) False because 'src' is not a valid environment variable. D) It raises a TypeError.** Answer: B Explanation: sys.path is a list of directory strings used for module search. The expression checks membership of the exact string 'src' in that list. Question 4. Which import statement correctly imports only the randint function from the random module and renames it to ri? A) import random as ri B) from random import randint as ri C) import randint from random as ri D) from random import * as ri Answer: B Explanation: from random import randint as ri imports the randint function and assigns it the local name ri. Question 5. After executing import math as m, which of the following will raise an AttributeError? A) m.sqrt(4) B) m.pi C) m.sin(0) D) m.random() Answer: D Explanation: The math module does not have a random attribute; that function belongs to the random module. Question 6. Consider the file pkg/__init__.py containing __all__ = ['mod1']. What is the effect of from pkg import *? A) It imports every submodule inside pkg.
C) pip get requests D) pip add requests Answer: B Explanation: -U (or --upgrade) tells pip to install the newest available version of the package. Question 10. After running pip uninstall numpy, which of the following is true? A) The numpy source files remain but cannot be imported. B) All compiled wheels for numpy are removed from the environment. C) The command only deactivates numpy for the current session. D) Pip will ask for confirmation before removing the package. Answer: D Explanation: By default, pip uninstall prompts the user to confirm deletion of the package files. Question 11. Which of the following best describes a syntax error in Python? A) An error raised when a function receives an unexpected argument type. B) An error detected by the interpreter before code execution begins. C) An exception that can be caught with a try…except block. D) An error that occurs only when an external library is missing. Answer: B Explanation: Syntax errors are detected during parsing, before any code runs, and abort execution. Question 12. In a try…except…else…finally block, which clause runs only if no exception occurs? A) try B) except C) else
D) finally Answer: C Explanation: The else block executes after the try block finishes without raising an exception. **Question 13. Which built-in exception is the direct parent of ZeroDivisionError? ** A) ArithmeticError B) ValueError C) Exception D) BaseException Answer: A Explanation: ZeroDivisionError inherits from ArithmeticError, which in turn inherits from Exception. **Question 14. What will be the output of the following code?
try: raise ValueError("bad") except Exception as e: print(type(e).__name__)A) BaseException B) Exception C) ValueError D) RuntimeError Answer: C Explanation: The caught exception e is a ValueError; type(e).__name__ returns its class name.
Question 18. Which method removes all leading and trailing whitespace characters from a string? A) strip() B) trim() C) replace(' ', '') D) lstrip() Answer: A Explanation: strip() returns a copy of the string without leading and trailing whitespace. Question 19. Given s = "abracadabra", what does s.find("cad") return? A) 3 B) 4 C) -1 D) 7 Answer: A Explanation: find returns the lowest index where the substring starts; "cad" begins at position 3. **Question 20. Which of the following statements about Python strings is false? ** A) Strings are immutable; any modification creates a new object. B) The in operator checks for substring presence. C) str.isnumeric() returns True for Roman numerals. D) Concatenation with + creates a new string. Answer: C Explanation: isnumeric() returns True for Unicode characters representing numbers, not for Roman numeral letters like “IV”.
Question 21. What does the list comprehension [x**2 for x in range(5) if x %2==0] produce? A) [0, 1, 4, 9, 16] B) [0, 4, 16] C) [1, 9, 25] D) [0, 2, 4] Answer: B Explanation: The comprehension squares each even x (0,2,4), resulting in [0, 4, 16]. Question 22. Which expression creates a shallow copy of list a? A) a.clone() B) list(a) C) a.copy() D) Both B and C are correct. Answer: D Explanation: Both list(a) and a.copy() return shallow copies of the list. Question 23. After executing lst = [1, 2, 3, 4]; del lst[1:3], what is the content of lst? A) [1, 2, 3, 4] B) [1, 4] C) [2, 3] D) [1, 2, 3] Answer: B Explanation: del lst[1:3] removes elements at indices 1 and 2 (values 2 and 3), leaving [1, 4].
Answer: C Explanation: Lambda functions are anonymous, single-expression functions; the expression’s value is implicitly returned. Question 27. In object-oriented Python, which of the following correctly defines a class variable counter shared by all instances? A) self.counter = 0 inside __init__ B) counter = 0 directly under the class definition C) self.__counter = 0 inside a method D) global counter; counter = 0 inside a method Answer: B Explanation: Variables defined directly in the class body are class variables, shared across all instances. Question 28. What is the effect of name mangling on an attribute named __value inside class MyClass? A) It becomes _MyClass__value. B) It stays __value. C) It becomes __MyClass__value. D) It is removed from the instance dictionary. Answer: A Explanation: Python rewrites attributes with double leading underscores (and no trailing underscores) to _ClassName__attr to avoid accidental overrides in subclasses. Question 29. Which built-in function can be used to determine whether an object obj is an instance of class MyClass or one of its subclasses? A) type(obj) == MyClass B) isinstance(obj, MyClass) C) issubclass(obj, MyClass)
D) hasattr(obj, '__class__') Answer: B Explanation: isinstance returns True for objects whose class is MyClass or any subclass thereof. Question 30. What does super().__init__(value) do inside a subclass’s __init__ method? A) Calls the subclass’s own __init__ recursively. B) Calls the parent class’s __init__ with the argument value. C) Returns a new instance of the parent class. D) Creates a static method named __init__. Answer: B Explanation: super() returns a proxy object that delegates method calls to the next class in the MRO; here it invokes the parent’s initializer. Question 31. Which of the following statements about multiple inheritance in Python is false? A) The method resolution order (MRO) is computed using C3 linearization. B) All base classes are initialized automatically without explicit calls. C) A subclass can inherit from more than one parent class. D) super() works with multiple inheritance following the MRO. Answer: B Explanation: Python does not automatically call each base class’s __init__; the subclass must explicitly invoke them (often via super()). **Question 32. Given the classes:
class A: def foo(self): print("A") ## Programming PCAP Ultimate ## Exam C) The class dictionary of `obj`. D) The memory address of `obj`. Answer: B Explanation: `__dict__` holds the writable attribute namespace of an object (instance attributes). **Question 35. Which of the following statements about iterators is **true**?** A) An iterator must implement `__len__`. B) The `next()` built-in function works on any iterable. C) An iterator implements both `__iter__()` and `__next__()`. D) A generator object cannot be an iterator. Answer: C Explanation: By definition, an iterator implements `__iter__` (returning itself) and `__next__` (producing the next value or raising `StopIteration`). **Question 36. What will the following generator produce? ```python def gen(): for i in range(3): yield i * iA) A list [0, 1, 4] B) An iterator that yields 0, 1, 4 on successive next() calls C) A function object that returns the tuple (0,1,4) D) Nothing; yield is invalid outside a function. Answer: B Explanation: gen() returns a generator object; each next() call yields the next squared number until the loop ends.
Question 37. Which expression creates a generator expression equivalent to [x* for x in range(5)]? A) {x*2 for x in range(5)} B) (x*2 for x in range(5)) C) list(x*2 for x in range(5)) D) generator(x*2 for x in range(5)) Answer: B Explanation: Parentheses around a comprehension create a generator expression. Question 38. In the context manager statement with open('data.txt', 'r') as f:, what method is called on the file object when exiting the block? A) f.close() automatically. B) f.flush() automatically. C) f.__exit__() automatically. D) No method is called; the file stays open. Answer: A Explanation: The file object’s __exit__ method calls close(), ensuring the file is closed when the block ends. Question 39. Which mode opens a file for appending binary data without truncating existing contents? A) 'wb' B) 'ab' C) 'r+b' D) 'w+b' Answer: B Explanation: 'a' stands for append; adding 'b' makes it binary. The file pointer is positioned at the end and the file is not truncated.
Explanation: del math removes the name binding from the current namespace; the module object may still exist in sys.modules, but the name math is no longer defined, causing NameError. Question 43. Which of the following statements about the built-in enumerate function is correct? A) It returns a dictionary mapping indices to items. B) It can be used only with lists. C) It yields pairs (index, item) starting from 0 by default. D) It modifies the original iterable in place. Answer: C Explanation: enumerate(iterable, start=0) returns an iterator that produces (index, item) tuples. **Question 44. What does the following code output?
def outer(): x = 5 def inner(): nonlocal x x += 1 return x return inner() print(outer())A) 5 B) 6 C) NameError D) UnboundLocalError
Answer: B Explanation: nonlocal allows inner to modify the binding of x in the enclosing outer scope; x becomes 6 and is returned. Question 45. Which of the following statements about the assert keyword is true? A) assert statements are always executed, even when Python runs with the -O flag. B) assert raises a SyntaxError if the condition is false. C) assert raises an AssertionError when its condition evaluates to False. D) assert can only be used inside functions. Answer: C Explanation: assert condition, message evaluates the condition; if false, it raises AssertionError with the optional message. Question 46. What is the result of list(map(str.upper, ['a', 'b', 'c']))? A) ['A', 'B', 'C'] B) ['a', 'b', 'c'] C) ['a', 'b', 'c'] with each element converted to uppercase in place. D) An error because str.upper is not callable. Answer: A Explanation: map applies the str.upper method to each element, producing an iterator; list materializes it as ['A','B','C']. Question 47. Which of the following is the correct way to read a file line-by-line without loading the whole file into memory? A) data = f.read().splitlines() B) for line in f.readlines(): C) for line in f:
Answer: A Explanation: reversed(iterable) returns a reverse iterator; it works for sequences and any object implementing __reversed__ or __len__/__getitem__. **Question 51. What is the output of the following code?
def f(): try: return 1 finally: return 2 print(f())A) 1 B) 2 C) None D) Raises a SyntaxError. Answer: B Explanation: The finally block executes after the try block and its return value overrides the earlier return. Question 52. Which of the following is the correct way to catch any exception without stopping the program? A) except: B) except Exception: C) except BaseException: D) Both B and C are acceptable, but B is preferred. Answer: D
Explanation: except Exception: catches most user-level exceptions; except BaseException: also catches system-exit events, which is usually undesirable. The bare except: is discouraged. Question 53. What does the hash() built-in function do when applied to an immutable object like a tuple? A) Returns the memory address of the object. B) Computes a hash value based on the contents, suitable for dictionary keys. C) Converts the tuple to a string. D) Raises a TypeError because tuples are unhashable. Answer: B Explanation: Immutable objects implement __hash__; hash() returns an integer derived from the object’s contents. Question 54. Which of the following statements about the __repr__ method is correct? A) __repr__ must return a string that, when passed to eval, recreates the object. B) __repr__ is used by the print function. C) If __repr__ is not defined, Python falls back to __str__. D) __repr__ is only called for built-in types. Answer: A (with nuance) Explanation: The official recommendation is that __repr__ return a string that could be used to recreate the object; it is also the default representation shown in the interactive interpreter. If __repr__ is missing, Python uses the default object representation. Question 55. Which of the following is a correct way to create a property named area that computes self.width * self.height in a class? A)