0% found this document useful (0 votes)
2 views10 pages

Python Question Bank

The document is a comprehensive question bank divided into five units, covering various topics in Python programming, including concepts like functions, data structures, object-oriented programming, NumPy, pandas, and Matplotlib. Each unit contains two-mark, five-mark, and ten-mark questions that assess understanding and application of the material. The questions range from basic definitions and code examples to complex implementations and comparisons of programming paradigms.

Uploaded by

sakthi8164
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views10 pages

Python Question Bank

The document is a comprehensive question bank divided into five units, covering various topics in Python programming, including concepts like functions, data structures, object-oriented programming, NumPy, pandas, and Matplotlib. Each unit contains two-mark, five-mark, and ten-mark questions that assess understanding and application of the material. The questions range from basic definitions and code examples to complex implementations and comparisons of programming paradigms.

Uploaded by

sakthi8164
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

Two mark question bank

UNIT I
1. State the primary function of the `__name__` variable during module execution in
Python.
2. Describe the bytecode generation step when a Python file is run.
3. Explain the difference between `break` and `continue` statements in loops.
4. When does a `for` loop in Python execute the optional `else` block?
5. How can short-circuit evaluation be exploited in conditional branching?
6. Give an example of a list comprehension that produces the squares of odd numbers
below 20.
7. Why are lists considered mutable while tuples are not?
8. What is the purpose of a lambda expression in functional style programming?
9. Show how default argument values can lead to unexpected behaviour with mutable
objects.
10. Define recursion and mention one limitation when using recursion in Python.
11. Distinguish between positional-only and keyword-only parameters.
12. What is the importance of indentation in Python’s program structure?
13. How is integer division different from floor division in Python 3?
14. Identify two built-in functions that can be used to create iterable objects from numeric
ranges.
15. Write an example that demonstrates unpacking of a list into separate variables.
16. Explain how the `pass` statement can be useful in iterative program design.
17. What is a docstring and where is it stored at runtime?
18. Describe how `id()` can be used to illustrate mutability.
19. Explain the concept of “truthy” and “falsy” objects in branching.
20. Provide a single-line expression that returns the maximum of two numbers without
using `if`.
21. Why is tail recursion not optimized in CPython?
22. What side effect does the expression `[None]*5` have when used to create a matrix?
23. Illustrate the use of the walrus operator (`:=`) inside a `while` loop condition.
24. How does `enumerate()` improve readability in loop constructs?
25. Compare shallow copy and deep copy for nested list structures.

UNIT II
26. Differentiate between sequence unpacking and multiple assignment.
27. Explain why strings are considered sequence types yet immutable.
28. State two advantages of using `set` over `list` when membership testing is frequent.
29. Provide a code snippet that converts a list with duplicate values into one that preserves
unique insertion order.
30. What is the difference between a shallow copy and a view returned by slicing?
31. Show how a dictionary comprehension can invert keys and values safely.
32. How does Python resolve attribute lookup in a multiple inheritance hierarchy (MRO)?
33. What built-in function can be used to verify subclass relationships dynamically?
34. Explain purpose of `__slots__` in class definitions.
35. Why must user-defined classes inherit from `Exception` to create custom exceptions?
36. Provide two reasons to prefer `isinstance()` over `type()` in OOP designs.
37. Describe how `frozenset` differs from `set` and give a use case.
38. What is the functional difference between `dir(obj)` and `vars(obj)`?
39. How does `*` unpacking work inside a function call?
40. Give an example where overriding `__str__` is useful for debugging.
41. What is the role of the `super()` function in cooperative multiple inheritance?
42. Explain duck typing with a concise example.
43. How can a regular expression be used to extract all email addresses from a string?
44. Distinguish greedy versus non-greedy quantifiers in regex.
45. What does the `re.MULTILINE` flag modify in pattern matching?
46. Mention two limitations of using lists to emulate sets.
47. Name the protocol method that implements containment testing (`in`) for user-defined
objects.
48. Explain attribute shadowing in class inheritance.
49. Why is it recommended to derive custom exceptions from `BaseException` children
rather than `BaseException` itself?
50. How do you prevent a dictionary from raising a `KeyError` for missing keys without
using `try/except`?

UNIT III
51. Distinguish between `np.array` and `np.asarray`.
52. Explain broadcasting with a two-sentence example.
53. What is the difference between `np.zeros` and `np.empty`?
54. State why `dtype` is critical when reading binary data into NumPy.
55. Describe the role of `axis` parameter in reduction operations.
56. Provide a one-liner that generates a 5×5 identity matrix.
57. What are boolean masks and how are they created?
58. Explain the memory implication of fancy indexing compared with slicing.
59. When will `np.sort` return a copy rather than view?
60. How can structured arrays store heterogeneous data types?
61. Give an example where `np.vectorize` may not improve performance.
62. Describe the difference between `view()` and `copy()` on arrays.
63. What is the effect of setting `order='F'` when creating arrays?
64. Show how to compute element-wise logical XOR between two boolean arrays.
65. Why should Python’s built-in `sum` be avoided on NumPy arrays?
66. What does `np.set_printoptions` change, and does it affect array data?
67. Use a single expression to clip all values of an array between 0 and 1.
68. How does `np.argmax` handle ties?
69. Explain the difference between bit-wise and logical operations on boolean arrays.
70. Why is `np.random.default_rng()` preferred to legacy random functions?
71. What does `keepdims=True` accomplish in aggregation?
72. Provide a code snippet to reshape a 1D array of length 27 into a 3×3×3 cube.
73. How does the `flags` attribute reveal array mutability?
74. State one caveat when comparing floating-point arrays for equality.
75. What is `np.mgrid` used for?

UNIT IV
76. What is the difference between a `Series` and a single-column `DataFrame`?
77. How does `loc` differ from `iloc` for slicing?
78. Explain the purpose of the `axis` argument in `DataFrame.apply`.
79. State the default alignment behaviour when adding two `Series` with different indexes.
80. What advantage does `Categorical` datatype bring over plain object dtype?
81. Describe what a hierarchical index (MultiIndex) looks like.
82. Provide an idiom for forward-filling missing values.
83. How does `join='outer'` differ from `join='inner'` in `concat`?
84. What does `value_counts` return?
85. Give an example of broadcasting across rows using `DataFrame.sub` with `axis=0`.
86. Why might `df.eval("a + b")` be faster than `df['a'] + df['b']`?
87. What parameter enables vectorized string methods to ignore case?
88. Explain what `groupby.transform` returns compared with `groupby.apply`.
89. How can you construct a pivot table keyed on two columns?
90. State the purpose of `asfreq` in time series.
91. What is the difference between `between_time` and `between`?
92. Provide a one-liner to read only the first 100 rows of a CSV file.
93. What does `inplace=True` technically mean for DataFrame operations?
94. How does `.at` differ from `.loc` for scalar access?
95. Explain why chained assignment may yield warnings.
96. Show how `query` can be used to filter using a variable from the outer scope.
97. What is the difference between `rolling` and `expanding` windows?
98. Mention one advantage of using `pd.to_datetime` before plotting a time series.
99. How can you set multiple columns as index in a single operation?
100. Describe how to detect duplicate rows in a DataFrame.

UNIT V
101. Which Matplotlib object represents a single figure window?
102. Explain the difference between `plt.plot` and `ax.plot`.
103. What is the default backend in a non-interactive environment?
104. State the purpose of `tight_layout`.
105. How does `plt.subplot` differ from `plt.subplots`?
106. Provide a code snippet to annotate the maximum point on a line plot.
107. Describe the difference between `markersize` and `linewidth` arguments.
108. How can you invert the y-axis?
109. Explain the function of `plt.colorbar`.
110. What is a colormap and why choose perceptually uniform ones?
111. Show how to create a histogram with log-scaled y-axis.
112. What argument adds transparency to plotted markers?
113. How can you share the x-axis among multiple subplots?
114. What does the `%matplotlib inline` magic do in Jupyter?
115. Define a contour level in contour plots.
116. When do you need to call `ax.set_aspect('equal')`?
117. Describe how 3-D plotting is enabled in Matplotlib.
118. Provide an example for saving a figure with 300 DPI.
119. What is the effect of calling `plt.cla()`?
120. How do you switch to a different style sheet?
121. Explain why calling `plt.show()` is optional in notebooks.
122. How can legends be placed outside the plotting area?
123. What is the use of `zorder`?
124. Mention one benefit of using object-oriented interface over state-based.
125. How can you add Greek letters to axis labels?
Five mark question bank

UNIT I
126. Design an algorithm in Python that counts palindromic substrings in a given string
without using slicing inside the main loop; discuss time complexity.
127. Explain with code examples how first-class functions enable higher-order
programming patterns in Python.
128. Compare iterative and recursive implementations of computing the nth Fibonacci
number in terms of speed, memory, and readability.
129. Write a function that flattens an arbitrarily nested list using recursion and
generators, and explain why generators are preferable.
130. Demonstrate how list comprehensions can replace nested loops for matrix
transposition; analyse readability and performance.
131. Discuss the scope rules (LEGB) in Python by tracing the resolution of variables in a
nested function scenario that uses `nonlocal`.
132. Implement a menu-driven CLI program that manages a to-do list using
dictionary-based storage; show how exception handling makes it reliable.
133. Illustrate immutability pitfalls by modifying a function that uses a default list
argument; suggest robust alternatives.
134. Explain with code why tail recursion is not optimized in CPython and propose two
workarounds for deep recursion problems.
135. Develop a function that returns the union, intersection, and difference of two lists
without converting them to sets, and evaluate its complexity.

UNIT II
136. Compare `list`, `tuple`, and `array.array` with regard to memory footprint,
mutability, and speed; support claims with the `sys.getsizeof` function.
137. Implement a class `Polynomial` that supports addition and evaluation; focus on
operator overloading and encapsulation.
138. Describe the Method Resolution Order (MRO) in multiple inheritance with an
example using diamond hierarchy; include C3 linearization discussion.
139. Build a regular expression that validates IPv6 addresses; explain each component of
the pattern.
140. Explain how generators and iterators differ by implementing a custom iterator class
for prime numbers and a generator version; compare.
141. Discuss exception propagation in nested `try/except/finally` blocks; create code that
illustrates control flow for each handler.
142. Show how `collections.Counter` can simplify frequency analysis in large text corpora
compared with manual dictionary accumulation.
143. Design a class hierarchy for geometric shapes that demonstrates polymorphism
with an overridden `area()` method; include UML-style explanation.
144. Evaluate the trade-offs between using list comprehensions and the `map`/`filter`
higher-order functions for performance and readability.
145. Construct a mini-parser using `re` module that transforms dates from
“DD/MM/YYYY” to “YYYY-MM-DD”, handling invalid inputs gracefully.

UNIT III
146. Use vectorized operations in NumPy to estimate π using Monte Carlo simulation;
explain why loops are slower.
147. Demonstrate broadcasting by subtracting the mean of each column from a 2-D array
without explicit loops; justify each step.
148. Implement k-means clustering from scratch with NumPy arrays; highlight where
fancy indexing accelerates the algorithm.
149. Show how to detect and replace outliers in a dataset using median absolute
deviation with purely NumPy code.
150. Explain memory sharing in NumPy views by constructing two arrays that point to
the same data buffer and proving it with `np.may_share_memory`.
151. Illustrate the use of structured arrays by loading heterogeneous sensor data
(timestamp, temperature, status) and performing typed queries.
152. Compare the speed of matrix multiplication using `np.dot` and naive nested Python
loops for a 500×500 matrix; provide timing results.
153. Explain how `einsum` can eliminate intermediate arrays by expressing tensor
contractions; provide two common examples.
154. Build a boolean mask to extract rows of a 2-D array where the sum exceeds the
overall mean; analyse complexity.
155. Describe the differences between in-place and out-of-place arithmetic operations in
NumPy, and their effects on memory and performance.

UNIT IV
156. Prepare a step-by-step recipe to merge three DataFrames on different keys,
handling duplicates and suffix conflicts.
157. Use groupby and window functions to compute a 7-day rolling average of daily
sales, then plot the result; comment on gaps due to missing days.
158. Design a data cleaning pipeline that converts mixed-type columns to numeric, flags
impossible values, and logs the transformations.
159. Explain how hierarchical indexing facilitates cross-sectional operations with
examples on panel-style stock price data.
160. Demonstrate pivot tables by summarizing a large call-centre log into agent-level
statistics such as mean handling time and call count.
161. Compare performance of vectorized string methods versus applying pure Python
functions over a million-row DataFrame containing URLs.
162. Illustrate time-zone localization and conversion for time series data collected in
multiple regions, ensuring arithmetic operations remain correct.
163. Show how the `query` API can build dynamic filters from user input while avoiding
injection vulnerabilities; include benchmarks.
164. Implement an efficient left anti-join in Pandas and discuss when it is preferable to
use `merge` vs `isin`-based filtering.
165. Evaluate `eval` and `query` performance advantages using the `numexpr` engine for
large-scale arithmetic expressions.

UNIT V
166. Create a composite figure with a gridspec layout containing a histogram, scatter
plot, and heatmap sharing a common colour bar.
167. Demonstrate how to add interactive tooltips to Matplotlib plots using mplcursors or
other utilities; discuss limitations.
168. Explain how artists and the rendering pipeline work by dissecting what happens
internally when `plt.plot` is called.
169. Design a Matplotlib style sheet that adheres to journal guidelines (font sizes, line
widths, serif fonts) and show its application.
170. Illustrate techniques to avoid overplotting in large scatter plots, including alpha
blending, hexbin, and density estimation.
171. Implement a 3-D surface plot of a mathematical function and project its contour
onto the base plane; annotate key features.
172. Compare different methods of embedding Matplotlib figures into a Tkinter GUI;
outline the steps and challenges.
173. Discuss coordinate transformations between data, axes, and figure spaces with an
example placing an inset zoom.
174. Show how to animate a simulation of a damped harmonic oscillator and save it as an
MP4 using FuncAnimation.
175. Evaluate performance trade-offs between rasterization and vector graphics
backends when exporting complex figures.
Ten mark question bank

UNIT I
176. Develop a command-line password manager in pure Python that supports adding,
retrieving, and deleting credentials stored in a JSON file encrypted with a master
password; discuss design patterns, security considerations, and exception handling.
177. Analyse Python’s garbage collection mechanism—in particular reference counting
and the cyclic garbage collector—illustrating with experiments how circular references
are collected.
178. Build a mini language interpreter that evaluates arithmetic expressions using
recursive-descent parsing; explain grammar design and error handling.
179. Compare imperative, functional, and object-oriented paradigms in Python by
implementing statistical mean, median, and mode calculations in three styles; analyse
readability and extensibility.
180. Design and benchmark three different solutions (iterative, memoized recursion, and
dynamic programming) for computing the edit distance between two strings.
181. Implement a decorator that caches function results with time-based invalidation;
include tests showing its effects on runtime performance.
182. Critically evaluate Python’s Global Interpreter Lock (GIL), demonstrating with
multithreaded code when it is a bottleneck and how multiprocessing circumvents it.
183. Create an interactive text adventure game utilising classes, inheritance, and
polymorphism; document design decisions and future extensibility points.
184. Implement a coroutine-based producer-consumer pipeline using the `asyncio`
module, and measure throughput compared with synchronous code.
185. Using type hints and `mypy`, refactor a legacy codebase snippet of around 150 lines
to improve maintainability; discuss findings and remaining limitations.

UNIT II
186. Build a generic tree data structure supporting preorder, inorder, and postorder
traversals, and compare memory usage with a nested list implementation.
187. Develop a regular-expression-driven tokenizer that converts a subset of Markdown
to HTML; handle lists, emphasis, and links.
188. Architect and implement a plugin framework using abstract base classes where
plugins are discovered via entry points; demonstrate with at least two sample plugins.
189. Perform a comprehensive study on multiple inheritance conflicts, designing
experiments that show attribute and method resolution ambiguity and resolution via
MRO tweaking.
190. Implement a dynamic ORM-like layer that maps CSV files to class objects, providing
CRUD operations and validation using property descriptors.
191. Write a robust command-line argument parser without using `argparse`, leveraging
`sys.argv` and regular expressions; support optional flags, defaults, and subcommands.
192. Investigate memory profiling of various container types (`list`, `deque`, `array`,
`numpy.array`) when storing one million integers; present findings with plots.
193. Design a logging framework extension that logs to rotating files and remote syslog
servers, incorporating context managers and custom exceptions.
194. Implement a regex-based lexical analyser for arithmetic expressions, then refactor it
to use the `re.Scanner` class; discuss differences.
195. Create a class meta-programming example where a metaclass enforces method
naming conventions and automatically registers subclasses into a registry.

UNIT III
196. Implement principal component analysis (PCA) from scratch using NumPy, validate
against `sklearn` results, and discuss numerical stability.
197. Develop a convolution operation for 2-D images in NumPy without using SciPy;
benchmark with varying kernel sizes and explain stride tricks.
198. Create a multidimensional kd-tree for fast nearest-neighbour lookup entirely in
NumPy arrays; test performance against brute force.
199. Simulate and visualise the 2-D Ising model using vectorised NumPy code; analyse
phase transition behaviour.
200. Implement stochastic gradient descent for linear regression with minibatching and
compare convergence speed to closed-form solution.
201. Investigate cache friendliness of different array memory orders (`C` vs `F`) during
large linear algebra operations and summarise findings.
202. Build a partial differential equation solver for the 1-D heat equation using finite
differences; verify with analytical solution.
203. Optimise a computational pipeline with `numba` JIT compilation and quantify
speedups for a fractal generation task.
204. Design an experiment to measure the effect of NumPy’s `float32` vs `float64`
precision on training a simple neural network.
205. Implement a sparse matrix representation using coordinate (COO) format in NumPy
arrays and code matrix-vector multiplication; compare with SciPy’s sparse module.

UNIT IV
206. Design a scalable ETL process that ingests, cleans, and aggregates gigabyte-scale
CSV logs into a partitioned Parquet data lake using Pandas; address memory
constraints.
207. Build a time series forecasting pipeline that reads sensor data, resamples irregular
intervals, imputes missing values, and applies ARIMA; evaluate forecast accuracy.
208. Implement a generic data validation framework using Pandas extension arrays and
custom `dtype`, providing automatic coercion and error reporting.
209. Compare the performance and memory usage of `merge_asof` vs window join
techniques for aligning high-frequency trading data.
210. Create a dashboard-ready dataset by unpivoting, normalising, and aggregating
multi-sheet Excel workbooks; discuss automation strategies.
211. Using Pandas, replicate SQL window functions (ROW_NUMBER, LAG, LEAD) and
validate results against a SQLite backend.
212. Investigate the impact of categorical encoding (one-hot vs ordered codes) on
groupby aggregations over 100 million rows.
213. Implement a vectorised Monte Carlo portfolio simulation calculating VaR and CVaR;
visualise the distribution with seaborn or Matplotlib.
214. Develop a change-point detection algorithm for time series using rolling statistics
and evaluate on synthetic and real datasets.
215. Conduct a case study comparing memory usage between `object` dtype strings,
`Categorical`, and `ArrowString` in Pandas 2.0; present findings.

UNIT V
216. Build a fully annotated exploratory data analysis report for a multivariate dataset
using Matplotlib; include advanced layouts, linked brushing, and interactive legends.
217. Develop a custom 3-D projection that plots data on a spherical surface, then animate
the rotation; explain math and implementation details.
218. Implement a reusable plotting function that automatically selects plot type based on
data characteristics and outputs publication-quality figures.
219. Create a Matplotlib extension artist for drawing violin plots with kernel density
estimation enhancements; compare with default violinplot.
220. Investigate anti-aliasing and rasterization options for producing high-resolution
images for print; include performance benchmarks.
221. Build an interactive dashboard combining Matplotlib embedded in a Jupyter widget
framework; support dynamic data updates.
222. Implement a geospatial visualization overlaying choropleths and proportional
symbols, using Cartopy or Basemap within Matplotlib.
223. Design and evaluate different colormap choices for color-blind accessibility; make
recommendations and show transformations.
224. Produce an animation of Fourier series approximation of a square wave, allowing
user-controlled number of harmonics; export as GIF.
225. Integrate Matplotlib with LaTeX for consistent fonts and equations, automating PDF
output for academic papers.

You might also like