




























































































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!





























































































Question 1. Which special method is called automatically when a new instance of a class is created? A) del B) new C) init D) repr Answer: C Explanation: init is the constructor that initializes a newly created object after new has allocated it. **Question 2. What is the output of the following code?
class A: x = 5 a = A() print(a.x) ```** A) 5 B) None C) AttributeError D) 0 Answer: A Explanation: x is a class variable; instances can access it via attribute lookup. **Question 3. Which decorator turns a regular method into a class method?** ## Certifications CAPP CPPP Ultimate ## Exam A) @staticmethod B) @property C) @classmethod D) @abstractmethod Answer: C Explanation: @classmethod receives the class (cls) as its first argument instead of the instance. **Question 4. In Python, what does the __dict__ attribute of an object contain?** A) List of all methods B) Dictionary of the object’s writable attributes C) Tuple of base classes D) Source code of the class Answer: B Explanation: __dict__ stores a mapping of attribute names to their current values for that object. **Question 5. Which of the following statements about multiple inheritance is true?** A) Python resolves method calls using depth-first search only. B) The super() function cannot be used with multiple inheritance. C) The Method Resolution Order (MRO) can be inspected via the __mro__ attribute. D) All parent classes must be listed in alphabetical order. Answer: C ## Certifications CAPP CPPP Ultimate ## Exam D) pickle.write(obj, 'file.pkl') Answer: B Explanation: pickle works with binary streams; the file must be opened in 'wb' mode. **Question 9. What is a metaclass in Python?** A) A class that creates instances of other classes B) A function that decorates methods C) A built-in type used for type checking only D) A module that provides logging capabilities Answer: A Explanation: Metaclasses are classes of classes; they control class creation. **Question 10. Which descriptor method is called when an attribute is accessed on an instance?** A) __set__ B) __delete__ C) __get__ D) __init__ Answer: C Explanation: The __get__(self, instance, owner) method defines attribute read behavior. **Question 11. The sys.path list is used for which purpose?** A) Storing command-line arguments B) Defining the Python import search path ## Certifications CAPP CPPP Ultimate ## Exam C) Managing environment variables D) Registering installed packages Answer: B Explanation: sys.path contains directories that Python searches for modules to import. **Question 12. Which import statement imports only the sqrt function from the math module?** A) import math.sqrt B) from math import sqrt C) import sqrt from math D) import math as sqrt Answer: B Explanation: from module import name imports a specific attribute into the current namespace. **Question 13. What is the purpose of the __init__.py file in a package directory?** A) To declare the package’s version number B) To indicate that the directory should be treated as a Python package C) To list all sub-modules in the package D) To execute the package’s main function automatically Answer: B Explanation: Presence of __init__.py tells Python that the directory is a package (pre-PEP 420). ## Certifications CAPP CPPP Ultimate ## Exam Explanation: 5! = 5×4×3×2×1 = 120. **Question 17. Which function from the random module returns a random floating-point number in the range [0.0, 1.0)?** A) randint() B) random() C) uniform() D) randrange() Answer: B Explanation: random.random() returns a float in the half-open interval [0.0, 1.0). **Question 18. How can you retrieve the value of an environment variable named "HOME"?** A) os.getenv('HOME') B) sys.env['HOME'] C) os.environ('HOME') D) sys.getenv('HOME') Answer: A Explanation: os.getenv returns the value of an environment variable or None if it does not exist. **Question 19. Which exception is raised when an invalid literal is passed to int()?** A) TypeError B) ValueError C) SyntaxError ## Certifications CAPP CPPP Ultimate ## Exam D) AttributeError Answer: B Explanation: int('abc') raises ValueError because the string cannot be converted to an integer. **Question 20. In a try-except-else-finally block, when is the else clause executed?** A) Only if an exception occurs B) Only if no exception occurs in the try block C) Always, regardless of exceptions D) Only if the finally block raises an exception Answer: B Explanation: The else block runs when the try block completes without raising an exception. **Question 21. Which statement correctly raises a custom exception named MyError?** A) raise MyError() B) throw MyError() C) raise MyError D) MyError.raise() Answer: A Explanation: raise expects an exception instance (or class); MyError() creates the instance. **Question 22. What is the base class for most built-in exceptions in Python? ** ## Certifications CAPP CPPP Ultimate ## Exam **Question 25. Which logging level will capture all messages including debug information?** A) INFO B) WARNING C) DEBUG D) ERROR Answer: C Explanation: DEBUG is the lowest built-in level; configuring the logger to DEBUG captures all higher-level messages as well. **Question 26. How do you add a file handler to a logger named "app"?** A) logging.FileHandler('app.log') B) logger.addHandler(logging.FileHandler('app.log')) C) logging.addHandler('app.log') D) logger.setFile('app.log') Answer: B Explanation: You create a FileHandler and attach it to the logger via addHandler. **Question 27. Which function from the pdb module starts an interactive debugging session at the current line?** A) pdb.set_trace() B) pdb.debug() C) pdb.run() D) pdb.start() ## Certifications CAPP CPPP Ultimate ## Exam Answer: A Explanation: pdb.set_trace() drops you into the debugger at that point. **Question 28. What is the output of the following code? ```python s = "Python" print(s[0:3]) ```** A) Py B) Pyt C) Pyth D) Python Answer: B Explanation: Slice 0:3 returns characters at indices 0,1,2 → "Pyt". **Question 29. Which method returns a list of Unicode code points for each character in a string?** A) ord() B) chr() C) encode() D) decode() Answer: A Explanation: ord('A') returns the integer code point of a single character; applying it to each character yields the list. **Question 30. What does the re.search(r'\d+', 'abc42def') return?** ## Certifications CAPP CPPP Ultimate ## Exam **Question 33. Which comprehension creates a set of squares of numbers from 0 to 4?** A) {x**2 for x in range(5)} B) [x**2 for x in range(5)] C) (x**2 for x in range(5)) D) {x**2 for x in range(0,5,1)} Answer: A Explanation: Set comprehensions use curly braces; the expression generates {0,1,4,9,16}. **Question 34. What is a closure in Python?** A) A function that calls itself recursively B) A nested function that captures variables from its enclosing scope C) A class that encapsulates data and methods D) A decorator that modifies another function’s behavior Answer: B Explanation: A closure retains references to variables from the outer (enclosing) function even after that function has finished executing. **Question 35. Which lambda expression correctly doubles its input x?** A) lambda x: x * 2 B) lambda x: 2 + x C) lambda: x * 2 D) lambda x, y: x * y Answer: A Explanation: The lambda takes one argument x and returns x multiplied by 2. ## Certifications CAPP CPPP Ultimate ## Exam **Question 36. What does the following code print? ```python list(map(lambda n: n*3, [1,2,3])) ```** A) [1,2,3] B) [3,6,9] C) (3,6,9) D) {3,6,9} Answer: B Explanation: map applies the lambda to each element, producing a list of tripled numbers. **Question 37. Which mode opens a file for reading binary data?** A) 'r' B) 'rb' C) 'b' D) 'br' Answer: B Explanation: The 'b' flag indicates binary mode; combined with 'r' it opens for reading binary. **Question 38. What is the effect of using the with statement when opening a file?** A) It automatically creates the file if it does not exist. B) It locks the file for exclusive access. ## Certifications CAPP CPPP Ultimate ## Exam A) It lists the methods defined in the class. B) It shows the order in which base classes are searched for attributes. C) It is only available for new-style classes in Python 2. D) It can be modified at runtime to change inheritance. Answer: B Explanation: __mro__ (Method Resolution Order) is a tuple defining the linearization of base classes. **Question 42. What does the following code output? ```python class B: def __init__(self): self.__value = 10 def get(self): return self.__value b = B() print(b.get()) ```** A) 10 B) AttributeError C) NameError D) 0 Answer: A Explanation: Name mangling changes __value to _B__value, but the method accesses the mangled name correctly. ## Certifications CAPP CPPP Ultimate ## Exam **Question 43. Which statement correctly creates a static method called greet inside class Greeter?** A) @staticmethod def greet(): ... B) def greet(self): @staticmethod ... C) staticmethod def greet(): ... D) @classmethod def greet(): ... Answer: A Explanation: @staticmethod decorates a function that receives no implicit first argument. **Question 44. What will be printed? ```python def outer(): x = 5 def inner(): nonlocal x x = 10 inner() print(x) outer() ```** A) 5 B) 10 C) UnboundLocalError ## Certifications CAPP CPPP Ultimate ## Exam B) os.path.cwd() C) os.current_dir() D) os.getcwd() Answer: A Explanation: os.getcwd() returns the absolute path of the current working directory. **Question 48. What does sys.argv contain?** A) A dictionary of environment variables B) A list of command-line arguments passed to the script C) The version of the Python interpreter D) The list of imported modules Answer: B Explanation: sys.argv[0] is the script name; subsequent items are arguments. **Question 49. Which built-in function can be used to convert an integer to its binary string representation?** A) bin() B) hex() C) oct() D) str() Answer: A Explanation: bin(10) returns '0b1010'. **Question 50. What is the result of the expression `'Hello' * 3`?** ## Certifications CAPP CPPP Ultimate ## Exam A) 'HelloHelloHello' B) ['Hello', 'Hello', 'Hello'] C) ('Hello', 'Hello', 'Hello') D) TypeError Answer: A Explanation: Multiplying a string by an integer repeats it that many times. **Question 51. Which of the following statements creates a dictionary comprehension that maps numbers 0-3 to their squares?** A) {i: i*i for i in range(4)} B) [i: i*i for i in range(4)] C) (i: i*i for i in range(4)) D) {i*i for i in range(4)} Answer: A Explanation: Dictionary comprehensions use curly braces with key: value pairs. **Question 52. Which of these is the correct way to catch both ValueError and TypeError in a single except clause?** A) except (ValueError, TypeError): B) except ValueError or TypeError: C) except ValueError, TypeError: D) except [ValueError, TypeError]: Answer: A Explanation: A tuple of exception classes can be supplied to a single except clause.