






















































































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 exam verifies Python programming skills across syntax, functions, OOP, data structures, modules, file handling, error management, libraries (NumPy, Pandas, Matplotlib), and application development. Candidates solve coding problems, debug scripts, analyze algorithms, and interpret outputs. It includes practical scenarios for data manipulation, automation tasks, and logic-driven problem solving.
Typology: Exams
1 / 94
This page cannot be seen from the preview
Don't miss anything!























































































Question 1. Which of the following statements about the print() function in Python is TRUE? A) It returns the printed text as a string. B) It automatically appends a newline character after each call unless end is specified. C) It can only output numeric values. D) It does not exist in Python 3. Answer: B Explanation: In Python 3, print() adds a newline by default; this can be changed with the end parameter. Question 2. What will be the output of type(5 / 2)? A) <class 'int'> B) <class 'float'> C) <class 'complex'> D) <class 'bool'> Answer: B Explanation: The / operator always performs true division and returns a float. Question 3. Which of the following is a valid variable name in Python? A) 2nd_place B) first-place C) _total_sum D) total sum Answer: C Explanation: Variable names may start with a letter or underscore and cannot contain spaces or hyphens.
Question 4. What does the expression int('10') + float('5.5') evaluate to? A) 15.5 B) 105.5 C) 15 D) TypeError Answer: A Explanation: int('10') becomes 10, float('5.5') becomes 5.5; their sum is 15.5. Question 5. Which operator has the highest precedence? A) or B) and C) not D) == Answer: C Explanation: not is evaluated before and and or; comparison operators have lower precedence than not. Question 6. What is the result of 7 // 3? A) 2.333... B) 2 C) 3 D) 0 Answer: B
Answer: D Explanation: All three syntaxes produce a string containing a newline; triple quotes allow literal line breaks. Question 10. What will len('Python') return? A) 5 B) 6 C) 7 D) TypeError Answer: B Explanation: The string 'Python' has six characters. Question 11. Which of the following list methods modifies the list in place and returns None? A) sorted(lst) B) lst.sort() C) lst[::-1] D) list(lst) Answer: B Explanation: list.sort() sorts the list itself and returns None; sorted() returns a new list. Question 12. 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: It squares only even numbers (0,2,4) from the range, yielding [0,4,16]. Question 13. Which tuple operation will raise a TypeError? A) t = (1,2,3); t[0] = 10 B) t = (1,2); len(t) C) t = (); t + (4,) D) t = (1,); t * 3 Answer: A Explanation: Tuples are immutable; assigning to an index is illegal. Question 14. How can you unpack a tuple (a, b, c) into variables x, y, z? A) x, y, z = (a, b, c) B) x = y = z = (a, b, c) C) x, y, z = a, b, c D) Both A and C are valid. Answer: D Explanation: Both syntaxes assign each element to the corresponding variable. Question 15. Which dictionary method returns a view of the dictionary’s keys? A) dict.items() B) dict.values() C) dict.keys() D) dict.get() Answer: C
Question 19. Which statement correctly defines a function with a default argument? A) def f(a, b=10): B) def f(a=10, b): C) def f(a, =b): D) def f(a, b): =10 Answer: A Explanation: Default values must follow non‑default parameters. Question 20. How many positional arguments can be passed to a function defined as def foo(*args):? A) Exactly one B) Exactly two C) Any number, including zero D) Only keyword arguments are allowed Answer: C Explanation: *args collects an arbitrary number of positional arguments. Question 21. Which of the following lambda expressions correctly squares its input? A) lambda x: x ** 2 B) lambda x: x * x C) lambda x: pow(x,2) D) All of the above Answer: D Explanation: All three compute the square of x.
Question 22. What is the output of list(map(lambda x: x*2, [1,2,3]))? A) [1,2,3] B) [2,4,6] C) [0,1,2] D) TypeError Answer: B Explanation: map applies the lambda to each element, doubling them. Question 23. Which import statement correctly imports 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. Question 24. After executing import random as rnd, how would you call the randint function? A) random.randint(1,10) B) rnd.randint(1,10) C) randint(1,10) D) rnd.randomint(1,10) Answer: B Explanation: The module is aliased as rnd; its functions are accessed via that name.
Question 28. In a class, what is the purpose of the __init__ method? A) To define class-level constants. B) To initialize a new instance’s attributes. C) To destroy an instance. D) To overload the addition operator. Answer: B Explanation: __init__ runs automatically after an object is created, setting up its state. Question 29. Which statement correctly creates a subclass Dog of a base class Animal? A) class Dog(Animal): pass B) class Dog extends Animal: pass C) class Dog inherits Animal: pass D) class Dog - > Animal: pass Answer: A Explanation: Python uses parentheses to specify base classes. Question 30. How can you call the parent class’s initializer from a subclass? A) super().__init__() B) self.__init__() C) parent.__init__(self) D) Both A and C are valid. Answer: D Explanation: super() is the modern way; directly invoking the parent class also works. Question 31. Which of the following is an example of duck typing in Python?
A) Checking type(obj) == list before iterating. B) Using hasattr(obj, '__len__') to determine if len(obj) works. C) Requiring all objects to inherit from a common base class. D) Using static type annotations only. Answer: B Explanation: Duck typing relies on the presence of needed methods/attributes rather than explicit types. **Question 32. What will the following code print?
class A: def __len__(self): return 5 a = A() print(len(a)) ```** A) `5` B) `TypeError` C) `0` D) `None` Answer: A Explanation: `len()` calls the object's `__len__` method, which returns 5. **Question 33. Which exception is raised when trying to access a dictionary key that does not exist using square‑bracket notation?** A) `KeyError` B) To enforce a condition during debugging; raises `AssertionError` if false. C) To log a warning message. D) To permanently stop program execution. Answer: B Explanation: `assert` checks a condition and raises `AssertionError` when the condition is false. **Question 37. Which mode opens a file for reading binary data?** A) `'r'` B) `'rb'` C) `'w'` D) `'ab'` Answer: B Explanation: Adding `b` to the mode string selects binary mode. **Question 38. What does the `with open('data.txt') as f:` statement guarantee?** A) The file is opened in append mode. B) The file is automatically closed when the block ends. C) The file pointer is reset to the start after each iteration. D) The file is read-only regardless of the mode. Answer: B Explanation: The context manager ensures `f.close()` is called even if an exception occurs. **Question 39. Which method reads the entire contents of a file as a single string?** A) `readline()` B) `readlines()` C) `read()` D) `readall()` Answer: C Explanation: `read()` returns the whole file content as one string. **Question 40. How can you write a list of strings `lines` to a file, each on a new line, using a single call?** A) `f.write(lines)` B) `f.writelines(lines)` C) `f.write('\n'.join(lines))` D) Both B and C are correct. Answer: D Explanation: `writelines` writes each string as‑is; joining with `'\n'` also produces the desired result. **Question 41. Which standard library module provides functions to read and write CSV files?** A) `json` B) `csv` C) `pickle` D) `xml` Answer: B Explanation: The `csv` module handles comma‑separated value files. **Question 42. What does `json.dump(data, f)` do?** A) Serializes `data` to a JSON formatted string and returns it. B) Writes the JSON representation of `data` directly to the file object `f`. D) `StopIteration` error Answer: A Explanation: `next(c)` yields successive values `0` then `1`. **Question 45. Which statement about the `@decorator` syntax is correct?** A) It replaces the original function with the decorator’s return value. B) It calls the decorator after the function executes. C) It can only be used with built‑in decorators. D) It must appear inside the function body. Answer: A Explanation: The decorator receives the original function, returns a new callable that replaces it. **Question 46. What does the `functools.lru_cache` decorator provide?** A) Thread synchronization. B) Automatic memoization of function results. C) Logging of function calls. D) Conversion of a function into a generator. Answer: B Explanation: `lru_cache` caches recent calls to avoid recomputation. **Question 47. Which of the following creates a thread that runs `target_func`?** A) `threading.Thread(target=target_func).start()` B) `threading.run(target_func)` C) `Thread(target_func).begin()` D) `multiprocessing.Thread(target=target_func).run()` Answer: A Explanation: The `Thread` class from `threading` is instantiated with `target` and started with `.start()`. **Question 48. In NumPy, what is the shape of `np.array([[1,2,3],[4,5,6]])`?** A) `(2,)` B) `(3,2)` C) `(2,3)` D) `(6,)` Answer: C Explanation: The array has 2 rows and 3 columns, so its shape is `(2,3)`. **Question 49. Which NumPy function creates an array of ten zeros of type `float64`?** A) `np.zeros(10, dtype='float64')` B) `np.array(10, dtype='float64')` C) `np.empty(10).astype('float64')` D) `np.full(10, 0)` Answer: A Explanation: `np.zeros` directly creates an array filled with zeros. **Question 50. How would you select the second column of a 2‑D NumPy array `a`?** A) `a[:,1]` B) `a[1,:]` C) `a[1]` D) `a[:,2]` Answer: A Explanation: Direct assignment creates or overwrites a column. **Question 54. Which regular expression pattern matches a string that starts with “cat” followed by any three characters?** A) `r'^cat.{3}$'` B) `r'cat...'` C) `r'^cat.*$'` D) `r'cat\w{3}'` Answer: A Explanation: `^` anchors start, `.{3}` matches exactly three characters, `$` anchors end. **Question 55. What does `re.search(r'\d+', 'abc123def')` return?** A) A match object containing `'123'` B) `None` C) The index of the first digit D) A list of all digit substrings Answer: A Explanation: `search` finds the first occurrence of one or more digits. **Question 56. Which of the following statements about list slicing `lst[::‑1]` is true?** A) It returns a copy of `lst` in reverse order. B) It modifies `lst` in place. C) It raises a `SyntaxError`. D) It selects every second element. Answer: A Explanation: The slice with step `-1` creates a reversed copy. **Question 57. What will `bool([])` evaluate to?** A) `True` B) `False` C) `None` D) Raises `TypeError` Answer: B Explanation: Empty sequences are falsy. **Question 58. Which expression correctly checks if variable `x` is neither `None` nor zero?** A) `if x != None and x != 0:` B) `if x is not None and x != 0:` C) `if x` D) `if not x is None or x != 0:` Answer: B Explanation: `is not None` tests identity; combined with `and` ensures both conditions. **Question 59. Which of the following will raise a `ZeroDivisionError`?** A) `10 // 0` B) `10 % 0` C) `10 / 0` D) All of the above. Answer: D Explanation: Any division or modulo by zero triggers `ZeroDivisionError`.