0% found this document useful (0 votes)
4 views15 pages

Python Programming-Answer Keys Set2

The document is an answer key and evaluation schema for a Python programming exam at Dhanalakshmi Srinivasan University for B.Tech students in May 2026. It includes evaluation criteria for multiple-choice questions, theoretical explanations, code implementations, and error handling, along with detailed answers covering various Python programming concepts. The document is structured into two parts, with a focus on both theoretical and practical aspects of Python programming, including libraries like Pandas and Matplotlib.

Uploaded by

Jaya
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)
4 views15 pages

Python Programming-Answer Keys Set2

The document is an answer key and evaluation schema for a Python programming exam at Dhanalakshmi Srinivasan University for B.Tech students in May 2026. It includes evaluation criteria for multiple-choice questions, theoretical explanations, code implementations, and error handling, along with detailed answers covering various Python programming concepts. The document is structured into two parts, with a focus on both theoretical and practical aspects of Python programming, including libraries like Pandas and Matplotlib.

Uploaded by

Jaya
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

DHANALAKSHMI SRINIVASAN UNIVERSITY

School of Engineering and Technology


University Examinations - May 2026 (Regulation 2021)
ANSWER KEY & EVALUATION SCHEMA — SET 1
Programme: [Link] | Semester: II | Subject Code & Name: 21ACY01 & PYTHON PROGRAMMING
Maximum Marks: 100 | Duration: 3 Hours

_________________________________________________________________________________

PART A — EVALUATION SCHEMA & ANSWER KEY (10 x 2 = 20 Marks)


Schema Matrix:
• Full Marks (2/2): Accurate core explanation with appropriate syntax/examples.
• Partial Marks (1/2): Incomplete explanation or code fragment omissions.

1. State any two major advantages of using Python programming language. [CO1, L1]
Answer (Any two points):
1. Simple, Readable Syntax: Resembles plain English which minimizes code maintenance costs.
2. Rich Library Ecosystem: Provides strong out-of-the-box suites for data systems and analysis (e.g.,
NumPy, Pandas, Matplotlib).
3. Interpreted Framework: Facilitates rapid testing and deployment because instructions are
executed line-by-line without an explicit compilation step.

2. What is the purpose of using functions in Python code? [CO1, L1]


Answer:
1. Code Reusability: Code segments can be defined once and invoked repeatedly across multiple
execution paths.
2. Modularity & Organization: Breaks down complex enterprise architectures into distinct,
maintainable sub-units.

3. How do you take a basic user string input using the Python input() function? [CO2, L2]
Answer:
The native input() wrapper function reads incoming terminal keystreams directly as a string format
object.
user_entry = input("Enter username: ")
print("Hello, " + user_entry)

4. Define the Boolean data type with a small, clear example code snippet. [CO2, L1]
Answer:
A Boolean data type tracks standard true/false binary evaluation primitives using keywords True or
False.
is_valid = True
print(type(is_valid)) # Output: <class 'bool'>

Dhanalakshmi Srinivasan University — Python Programming Answer Key System (May 2026)
5. What is a Series object in the Pandas library? [CO3, L1]
Answer:
A Pandas Series is an optimized, one-dimensional labeled array collection structured to host
homogeneous data vectors combined with an explicit index tracking axis layer.

6. Write down the simple basic syntax to merge two Data Frames in Pandas. [CO3, L2]
Answer:
Syntax configuration executing column/index relational merges:
(Alternative syntax: [Link](df2, on='key'))
merged_df = [Link](df1, df2, on='common_column')

7. Define what a syntax error is in Python with an easy practical example. [CO4, L1]
Answer:
A structural parsing exception raised by the interpreter when source code coordinates violate the
grammatical formatting specifications of the language.
if True # Missing a terminal block colon
print('Hello')

8. Explain the explicit use of the try and except blocks for error handling. [CO4, L2]
Answer:
1. try block: Encloses computational lines presenting potential runtime structural risk of generating
exceptions.
2. except block: Formulates handling responses that capture matching exception instances to avoid
program crash failure.

9. Mention any two standard data plots that can be generated using the matplotlib library. [CO5, L1]
Answer (Any two):
1. Line Plot
2. Vertical/Horizontal Bar Chart
3. Scatter Plot
4. Histogram / Pie Chart

10. Briefly define what linear regression means within a standard data analytics context. [CO5, L1]
Answer:
An optimization and modeling approach utilized to discover and map a stable linear mathematical
expression connecting a targeted continuous response variable (y) to an independent variable (X) via
an equation format (y = mx + c).

PART B — EVALUATION SCHEMA & DETAILED KEY (5 x 16 = 80 Marks)


Schema Matrix Per Question Block:
• Theoretical Analysis & Conceptual Definitions: 6 Marks
• Structural Logic & Syntactical Layout: 4 Marks

Dhanalakshmi Srinivasan University — Python Programming Answer Key System (May 2026)
• Implementation Accuracy & Code Correctness: 4 Marks
• Trace Execution Steps / Program Output Verification: 2 Marks

11 a. Explain the foundational structure of Python scripts and write an easy program using basic
mathematical arithmetic operators (+, -, *, /) to compute simple equations. [CO1, L2]
Answer Elements:
• Core Theory (6M): Detailing import segments, variable scoping allocations, module setups, logic
procedures, and the application invocation wrapper (if __name__ == '__main__':).
• Arithmetic Mapping (4M): Explicit actions of structural mathematical elements (+, -, *, /).
• Implementation (4M): See code below.
• Verification (2M): Expected output: Add: 15, Sub: 5, Mul: 50, Div: 2.0
def execute_arithmetic(val1, val2):
addition = val1 + val2
subtraction = val1 - val2
multiplication = val1 * val2
division = val1 / val2 if val2 != 0 else 'Error'
return addition, subtraction, multiplication, division

if __name__ == '__main__':
res_add, res_sub, res_mul, res_div = execute_arithmetic(10, 5)
print(f'Add: {res_add}, Sub: {res_sub}, Mul: {res_mul}, Div:
{res_div}')

11 b. OR: Discuss the conditional flow statements (if-else) and basic loop control constructs (for and
while loops) in Python with straightforward code examples. [CO1, L2]
Answer Elements:
• Core Theory (6M): Outlines if-else branching based on true/false evaluation states, and loops for
fixed data iterations (for) or ongoing state checking (while).
• Syntactical Layout (4M): Addresses mandatory block indentation syntax and loop control flags.
• Implementation (4M): See structural scripts below.
• Output Verification (2M): Visualizing print execution logs across each test scenario.
# Branching Structure
score = 82
if score >= 50:
print('Status: Pass')
else:
print('Status: Fail')

# Determinate Data Loop


for step in range(1, 4):
print(f'For Iteration: {step}')

# Indeterminate State Loop


count = 2
while count > 0:

Dhanalakshmi Srinivasan University — Python Programming Answer Key System (May 2026)
print(f'While Countdown: {count}')
count -= 1

12 a. Explain in detail how while loops and multi-conditional logical statements (if-elif-else) run in
Python. Provide a clear, step-by-step example. [CO2, L2]
Answer Elements:
• Core Theory (6M): Evaluates sequential branching inside loops. Explains that when a condition
matches, alternatives are skipped.
• Logic Script (4M): See below.
• Trace Execution Matrix (6M): Step-by-step state check analysis:
- Step 1: metric=3 -> 3>0 (True) -> matches if -> Prints 'Priority: High' -> updates metric to 2.
- Step 2: metric=2 -> 2>0 (True) -> matches elif -> Prints 'Priority: Medium' -> updates metric to 1.
- Step 3: metric=1 -> 1>0 (True) -> executes else -> Prints 'Priority: Low' -> updates metric to 0.
- Step 4: metric=0 -> 0>0 (False) -> Breaks loop cleanly.
metric = 3
while metric > 0:
if metric == 3:
print('Priority: High')
elif metric == 2:
print('Priority: Medium')
else:
print('Priority: Low')
metric -= 1

12 b. OR: What are Python Lists? Describe how to create a list, access its index elements, and execute
basic list operations like appending and slicing with easy code fragments. [CO2, L2]
Answer Elements:
• Core Theory (6M): Defines mutable, ordered collections processing zero-indexed coordinate
tracking indexes.
• Operations Logic (4M): Appending updates elements in-place; slicing takes sequences out via sub-
boundaries [start:stop].
• Implementation (4M): See code below.
• Output Verification (2M): Head: 10, Tail: 30, Sliced: [20, 30]
data_list = [10, 20, 30]
print(f'Head: {data_list[0]}, Tail: {data_list[-1]}')

data_list.append(40) # In-place extension


sub_slice = data_list[1:3] # Captures index values 1 and 2
print(f'Sliced: {sub_slice}')

13 a. What is the Pandas library? Describe the complete process of creating and accessing tabular data
fields inside a Pandas DataFrame using a basic sample database layout. [CO3, L3]
Answer Elements:
• Core Theory (6M): Explains Pandas structures optimized for high-performance structured database

Dhanalakshmi Srinivasan University — Python Programming Answer Key System (May 2026)
tracking layouts.
• Database Layout Design (4M): Maps nested dict models directly into table transformations.
• Implementation (4M): See code below.
• Output Verification (2M): Demonstrates label column and row extraction parsing via .loc
selections.
import pandas as pd

raw_db = {
'Emp_ID': [101, 102],
'Name': ['Alice', 'Bob'],
'Dept': ['HR', 'IT']
}
df = [Link](raw_db)
print(df)
print('Target Cell:', [Link][1, 'Dept']) # Accesses Row index 1 'Dept'
-> IT

13 b. OR: Elaborate on how grouping, aggregation, and data joining/merging tasks are performed
step-by-step using standard functions in the Python Pandas toolbox. [CO3, L3]
Answer Elements:
• Core Theory (6M): Split-Apply-Combine patterns using groupby(), reducing records with summary
aggregates, and blending data files with merge().
• Program Setup (4M): Builds explicit table dependencies linked by identity relational keys.
• Implementation (4M): See code below.
• Output Verification (2M): Prints unified aggregate totals joined with matching descriptive indexes.
import pandas as pd

df_sales = [Link]({'ID': [1, 2, 1], 'Sales': [100, 200, 150]})


df_names = [Link]({'ID': [1, 2], 'Emp': ['John', 'Jane']})

grouped = df_sales.groupby('ID').sum().reset_index()
final_df = [Link](grouped, df_names, on='ID')
print(final_df)

14 a. Write a detailed note on basic error handling logic in Python. Demonstrate how the structural
blocks of try, except, and finally operate to handle runtime errors. [CO4, L3]
Answer Elements:
• Core Theory (6M): Explains handling workflows. try isolates unsafe lines, except runs fallback
resolutions, and finally handles core system cleanups like closing active database connections.
• Logic Script (4M): See below.
• Output & Trace Verification (6M — 4M trace + 2M print logs):
- Scenario 1 (Normal): try runs -> except skipped -> finally prints -> returns calculations.
- Scenario 2 (Exception): try fails -> goes to except -> captures mistake -> finally prints -> returns
None.

Dhanalakshmi Srinivasan University — Python Programming Answer Key System (May 2026)
def compute_safe_div(x, y):
try:
print('[Try] Initializing')
output = x / y
except ZeroDivisionError as error:
print(f'[Except] Caught error: {error}')
output = None
finally:
print('[Finally] Cleanup complete')
return output

print('Result Normal:', compute_safe_div(10, 2))


print('Result Zero:', compute_safe_div(10, 0))

14 b. OR: Analyze common error classes encountered by learners while writing Python scripts (such as
NameError, TypeError, and IndexError) with simple code examples. [CO4, L3]
Answer Elements:
• Core Theory (6M): NameError (missing variable mappings), TypeError (mismatched operations on
values), IndexError (accessing collections out of range).
• Code Scenarios (6M): Explains and isolated code snippets.
• Script Correctness (4M): Complete code architecture testing error states safely.
try:
print(undefined_token) # Raises NameError
except NameError as e: print('Error caught:', e)

try:
result = 'String' + 10 # Raises TypeError
except TypeError as e: print('Error caught:', e)

try:
arr = [1, 2]
print(arr[5]) # Raises IndexError
except IndexError as e: print('Error caught:', e)

15 a. Explain how data visualization is implemented via the matplotlib library. Provide a short, easy
sample program script to produce a simple line plot and a vertical bar chart. [CO5, L3]
Answer Elements:
• Core Theory (6M): Explains rendering pipelines using the pyplot module, coordinate mapping, title
injection, axis formatting, and display flush operations (show()).
• Implementation (8M — 4M per plot template): Complete, valid plot architectures.
• Verification (2M): Detailed description of geometric features generated across line targets and
categorical bars.
import [Link] as plt

# Line Chart Module


[Link]([1, 2, 3], [10, 20, 15], marker='o', color='b')

Dhanalakshmi Srinivasan University — Python Programming Answer Key System (May 2026)
[Link]('Line Experiment')
[Link]()

# Bar Chart Module


[Link](['Group X', 'Group Y'], [40, 70], color='green')
[Link]('Bar Experiment')
[Link]()

15 b. OR: Detail the analytical phases of building a basic Regression Analysis module inside Python
using a clear, real-world case study context (e.g., house prices or sales forecasting). [CO5, L3]
Answer Elements:
• Analytical Lifecycle Phases (8M): 1. Gathering & formatting continuous metrics. 2. Data cleansing &
dimension transformations. 3. Fitting parameters to build baseline models. 4. Computing predictive
metrics (e.g., MSE metrics or R² values).
• Pipeline Implementation (6M): Applied scikit-learn training architecture.
• Interpretation (2M): Describes the target formula ($y = wx + b$) and prediction verification output.
import numpy as np
from sklearn.linear_model import LinearRegression

# Case study: House Size (sq ft) vs Estimated Value ($k)


X_dimensions = [Link]([[1100], [1400], [1700], [2000]])
y_valuation = [Link]([250, 310, 370, 430])

regression_engine = LinearRegression()
regression_engine.fit(X_dimensions, y_valuation)

predicted_val = regression_engine.predict([Link]([[1500]]))
print(f'Forecasted Valuation for 1500 sq ft: ${predicted_val[0]:.2f}k')

Dhanalakshmi Srinivasan University — Python Programming Answer Key System (May 2026)
DHANALAKSHMI SRINIVASAN UNIVERSITY
School of Engineering and Technology
University Examinations - May 2026 (Regulation 2021)
ANSWER KEY & EVALUATION SCHEMA — SET 2
Programme: [Link] | Semester: II | Subject Code & Name: 21ACY01 & PYTHON PROGRAMMING
Maximum Marks: 100 | Duration: 3 Hours

_________________________________________________________________________________

PART A — EVALUATION SCHEMA & ANSWER KEY (10 x 2 = 20 Marks)


Schema Matrix:
• Full Marks (2/2): Accurate core explanation with appropriate syntax/examples.
• Partial Marks (1/2): Incomplete explanation or code fragment omissions.

1. List any two major structural limitations or disadvantages of Python. [CO1, L1]
Answer (Any two points):
1. Lower Execution Speeds: Because it is an interpreted language, it runs slower than compiled
systems like C/C++.
2. High Memory Utilization: Python uses dynamic typing and reference tracking, which increases
overall RAM overhead.
3. Mobile Deployment Restrictions: Python has limited native support for creating mobile device
applications.

2. What are Python variables? Give an example of declaring and initializing an integer variable. [CO1,
L1]
Answer:
Variables act as named pointers that reference dynamic memory storage locations allocated for
system data entries.
item_count = 45 # Declaration and initialization of an integer

3. Identify the explicit architectural role of the elif clause statement in conditional loops. [CO2, L1]
Answer:
The 'elif' (else-if) statement handles multi-stage conditional checks. It allows the program to inspect
alternative evaluation pathways sequentially immediately after an 'if' statement fails, preventing
cluttered nested logic structures.

4. What constitutes an infinite loop runtime scenario? Provide a short example utilizing a while loop.
[CO2, L2]
Answer:
An infinite loop scenario occurs when a repetitive statement block executes continuously because
its termination condition never evaluates to False.

Dhanalakshmi Srinivasan University — Python Programming Answer Key System (May 2026)
while True:
print("Looping indefinitely") # Warning: infinite run

5. List down the two foundational object data structures used extensively inside the Pandas
framework. [CO3, L1]
Answer:
1. Series: Structured to handle one-dimensional, homogeneous labeled data arrays.
2. DataFrame: Structured to handle multi-dimensional, heterogeneous tabular sheets with
spreadsheet-style layouts.

6. Differentiate clearly between cross-joining and data merging processes inside Pandas datasets.
[CO3, L2]
Answer:
• Data Merging: Integrates independent tables by identifying and matching records across shared
columns or common keys.
• Cross-Joining: Combines datasets by generating a Cartesian product, linking every row of the
primary table to all rows of the secondary table without needing a shared key column.

7. Mention two typical forms of runtime core exceptions generated inside unhandled Python
programs. [CO4, L1]
Answer (Any two):
1. ZeroDivisionError
2. ValueError
3. TypeError / IndexError
4. NameError / KeyError

8. What system error state is logged when a script accidentally invokes a division by zero process?
[CO4, L2]
Answer:
The system intercepts this calculation anomaly and raises a native runtime exception class labeled:
ZeroDivisionError.

9. Which specific standard tool library is primarily called to handle basic charts and graphics layout
plotting? [CO5, L1]
Answer:
The primary tool used is the '[Link]' sub-module contained within the broader matplotlib
library interface framework.

10. Briefly explain what a correlation matrix metrics sheet is intended to showcase in data analytics.
[CO5, L1]
Answer:
A correlation matrix displays a grid of statistical correlation coefficients. It visualizes the strength and
direction of linear dependencies across all numerical variables in a dataset, with values ranging from
-1.0 to +1.0.

Dhanalakshmi Srinivasan University — Python Programming Answer Key System (May 2026)
PART B — EVALUATION SCHEMA & DETAILED KEY (5 x 16 = 80 Marks)
11 a. Elaborate extensively on the key benefits and structural characteristics that make Python a
popular choice. Share a simple script that demonstrates basic text string operations. [CO1, L2]
Answer Elements:
• Core Theory (6M): Analyzes design principles: dynamic variable checking, cross-platform
performance, open-source setup, and high developer productivity.
• String Analytics (4M): Details string immutability, index parsing, slicing, and system manipulation
functions.
• Implementation (4M): See code below.
• Verification (2M): Verifies target transformations (Upper: PYTHON, Slice: PYTH).
if __name__ == '__main__':
base_str = 'Python'
upper_str = base_str.upper()
slice_str = base_str[0:4] # Extracts indexes 0 to 3
print(f'Upper: {upper_str}, Slice: {slice_str}')

11 b. OR: What are user-defined functions in Python? Explain step-by-step how to define a function,
assign parameter arguments, and extract returning properties with plain code examples. [CO1, L2]
Answer Elements:
• Core Theory (6M): Explains custom block encapsulation using the def keyword, scoping rules,
positional argument bindings, and how data passes back to callers using return statements.
• Logic Setup (4M): Details signature definition, colon terminations, and statement indentation
rules.
• Implementation (4M): See code below.
• Output Verification (2M): Evaluates correct processing execution (e.g., Result: 35).
def process_multiply(factor1, factor2):
"""Calculates product value return parameters."""
product_result = factor1 * factor2
return product_result

if __name__ == '__main__':
execution_output = process_multiply(7, 5)
print(f'Multiplication Engine Result: {execution_output}')

12 a. Describe the methods used to accept basic raw user keyboard values in Python. Outline explicit
conversion functions (typecasting) to cast strings into numerical formats. [CO2, L2]
Answer Elements:
• Core Theory (6M): Explains that input() captures terminal values as strings by default. Outlines
why typecasting wrapper functions (like int() and float()) are required to convert these inputs for
mathematical calculations.
• Logic Setup (4M): Explains potential crash risks if input text patterns do not match expected
numeric values.
• Implementation (4M): See script below.

Dhanalakshmi Srinivasan University — Python Programming Answer Key System (May 2026)
• Verification (2M): Traces input conversions, such as turning text string entry '20' into an actual
integer number 20.
# Simulating clean input reading and variable conversion
raw_entry = '25' # Simulates input('Enter Value: ')
converted_int = int(raw_entry)
squared_value = converted_int ** 2
print(f'Converted Variable Type: {type(converted_int)}, Squared:
{squared_value}')

12 b. OR: Develop an easy-to-follow Python program that structures an automated conditional choice
system using if-elif-else conditional parameters to read variables and process calculations. [CO2, L2]
Answer Elements:
• Core Theory (6M): Evaluates complex logical branching patterns where multiple conditions are
checked in sequence. Once a matching pathway evaluates to true, subsequent branches are
skipped.
• Logic Script (4M): See code below.
• Script Correctness (4M): Provides complete structure containing if, multiple elif checks, and an else
fallback.
• Verification (2M): Validates calculations for a targeted input key selection (e.g., matching option 'B'
processes multiplication).
calc_mode = 'B'
val1, val2 = 10, 4

if calc_mode == 'A':
res = val1 + val2
elif calc_mode == 'B':
res = val1 * val2
elif calc_mode == 'C':
res = val1 - val2
else:
res = 'Unsupported Operation'
print(f'Operational Result Selection [{calc_mode}]: {res}')

13 a. What is Exploratory Data Analysis (EDA)? Outline how multidimensional dataset fields are
loaded and structured within DataFrames during initial analysis sweeps. [CO3, L3]
Answer Elements:
• Core Theory (6M): Defines EDA as an initial analytical approach used to summarize a dataset's
main characteristics, uncover anomalies, test hypotheses, and verify underlying statistical
assumptions.
• Data Frame Layout (4M): Explains row index alignment vector models and column array
generation rules.
• Implementation (4M): Uses Pandas features to print structural layout overviews (head(), info(),
describe()).

Dhanalakshmi Srinivasan University — Python Programming Answer Key System (May 2026)
• Verification (2M): Expected output: Displays summary counts, null entries, and distribution details
across columns.
import pandas as pd

# Loading mock multidimensional analytics matrix sheets


analytics_data = {
'Age': [23, 45, 31, 22],
'Income': [50000, 82000, 61000, 48000]
}
df_sweep = [Link](analytics_data)
print('--- Top Records ---')
print(df_sweep.head(2))
print('\n--- Structural Describe Sweep ---')
print(df_sweep.describe())

13 b. OR: Discuss the exact sequence of code steps required to load structural input text data files,
generate sorted aggregations, and strip missing data entries using the Pandas framework. [CO3, L3]
Answer Elements:
• Sequence Steps (6M): 1. read_csv() ingestion pipelines. 2. dropna() handling to clear out row
records containing null metrics. 3. groupby() aggregates sorted via sort_values().
• Code Logic (4M): Uses sequential method chaining to perform clear pipeline operations.
• Implementation (4M): See code below.
• Verification (2M): Validates step output logs, from data ingestion to generating clean sorted
summaries.
import pandas as pd
import io

# Simulating a CSV file data stream parsing situation


csv_stream = 'Item,Sales\nWidgetA,150\nWidgetB,\nWidgetA,300'
df_loaded = pd.read_csv([Link](csv_stream))

# Step 1: Strip missing records


df_clean = df_loaded.dropna()

# Step 2: Generate sorted aggregations


df_agg = df_clean.groupby('Item').sum().sort_values(by='Sales',
ascending=False)
print(df_agg)

14 a. Draft an easy, robust script showing basic exception tracking workflows that gracefully catches
invalid numerical keyboard entries from users using customized matching blocks. [CO4, L3]
Answer Elements:
• Core Theory (6M): Catches numeric processing errors gracefully. Uses targeted exception catchers
to prevent scripts from crashing when processing invalid user input data strings.
• Code Logic (4M): Uses specific handling blocks (ValueError) instead of generic exception traps.

Dhanalakshmi Srinivasan University — Python Programming Answer Key System (May 2026)
• Implementation (4M): Complete code structure showing handling routines.
• Verification (2M): Demonstrates handling normal numerical entries successfully vs displaying clear
user error instructions when parsing invalid inputs.
def execute_keyboard_parse(mock_input):
try:
processed_num = float(mock_input)
output_metric = 100 / processed_num
print(f'Calculation success: {output_metric}')
except ValueError:
print('Error handled: System could not parse alphanumeric text
entries into floats.')
except ZeroDivisionError:
print('Error handled: Calculation contains division by zero
constraints.')

print('Test 1 (Valid Input):')


execute_keyboard_parse('5')
print('\nTest 2 (Invalid Alphanumeric text input):')
execute_keyboard_parse('ABC_Text')

14 b. OR: Elaborate on structural programming layout syntax mistakes, semantic flaws, and basic
structural system runtime exceptions that arise frequently during introductory script execution. [CO4,
L3]
Answer Elements:
• Classification Groups (6M): 1. Syntax Mistakes (detected during compile-time parsing). 2. Runtime
Errors (unhandled exceptions during execution). 3. Semantic Flaws (code runs completely but yields
incorrect logic results).
• Structural Code Examples (6M): Provides specific code clips demonstrating each issue group.
• Correctness Logic (4M): Implements safe tracking blocks to trace code faults.
• Verification (2M): Detailed log walkthrough mapping distinct differences across logic flaws vs text
code formatting bugs.
# 1. Syntax Error (Grammar structural code formatting mistake)
# Example text: def test_func() <- Missing structural colon formatting

# 2. Runtime Exception (Valid syntax structure but fails during


execution)
try:
zero_calc = 5 / 0
except ZeroDivisionError as e:
print('Runtime exception logged safely:', e)

# 3. Semantic Error (Valid code execution, but flawed business logic


calculations)
radius = 10
flawed_area = 2 * 3.14159 * radius # Intended Area (pi*r^2) but typed

Dhanalakshmi Srinivasan University — Python Programming Answer Key System (May 2026)
Circumference equation
print('Semantic Logic Defect Output:', flawed_area)

15 a. Explain the methodology used to engineer a basic line chart with clean visual parameters using
matplotlib (such as customizing titles, plot legends, axes indicators, and label elements). [CO5, L3]
Answer Elements:
• Core Theory (6M): Detailed breakdown of visual parameters: adjusting step sizes, mapping chart
elements, naming axis indices, configuring legends using label identifiers, and flushing output views
safely.
• Execution Syntax (4M): Uses clean parameter commands: legend(), xlabel(), title(), grid().
• Implementation (4M): See chart code structure below.
• Verification (2M): Describes the final image features, including custom labels, legend text
placement, and visual data plot lines.
import [Link] as plt

timeline_x = [2021, 2022, 2023, 2024]


metric_y = [12, 19, 32, 51]

[Link](timeline_x, metric_y, marker='x', linestyle='--', color='r',


label='Growth Baseline')
[Link]('Performance Metrics Evaluation Over Timeline Axis')
[Link]('Timeline Intervals (Years)')
[Link]('Scale Magnitudes')
[Link](loc='upper left')
[Link](True)
[Link]()

15 b. OR: Provide an easy-to-understand breakdown of standard data evaluation tasks by explaining a


default workflow template for implementing linear regression analysis step-by-step. [CO5, L3]
Answer Elements:
• Default Template Lifecycle Workflow (8M): Phase 1: Ingest records. Phase 2: Split data features
into input matrices and targets. Phase 3: Train model parameters using linear optimization solvers.
Phase 4: Predict unseen values and evaluate performance metrics.
• Pipeline Implementation (6M): Implements scikit-learn training workflows over a Sales target
variable case study.
• Interpretation (2M): Illustrates calculating prediction metrics against incoming inputs.
import numpy as np
from sklearn.linear_model import LinearRegression

# Case context: Marketing Spend ($k) vs Projected Sales Outcome Unit


Scales
X_spend_features = [Link]([[5], [15], [25], [35]])
y_sales_outcome = [Link]([15, 35, 55, 75])

# Pipeline Phase 1 & 2: Fit modeling parameters using training sets

Dhanalakshmi Srinivasan University — Python Programming Answer Key System (May 2026)
model_engine = LinearRegression()
model_engine.fit(X_spend_features, y_sales_outcome)

# Pipeline Phase 3 & 4: Execute predictive inference calculations


target_test_spend = [Link]([[20]])
sales_forecast = model_engine.predict(target_test_spend)
print(f'Sales Forecast for $20k budget: {sales_forecast[0]:.2f} Units')

Dhanalakshmi Srinivasan University — Python Programming Answer Key System (May 2026)

You might also like