XXXX X: Important Instructions To Examiners
XXXX X: Important Instructions To Examiners
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
Summer - 2025 EXAMINATION
Model Answer – Only for the Use of RAC Assessors
Subject Name: Programming With Python Subject Code: 22616
___________________________________________________________________________________________________________________
Q. Sub Marking
Answer
No. Q. N. Scheme
Page 1 of 32
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
Summer - 2025 EXAMINATION
Model Answer – Only for the Use of RAC Assessors
Subject Name: Programming With Python Subject Code: 22616
___________________________________________________________________________________________________________________
Q. Sub
Answer
XXXX
Marking
No. Q. N. Scheme
X
in scenarios where you need to know if a loop completed fully or was prematurely
stopped.
c) Enlist any four built in function of dictionary. 2M
Ans. Python includes following dictionary methods: Any four
1. clear() methods = ½ M
2. copy() each
3. fromkeys()
4. get()
5. items()
6. keys()
7. pop()
8. popitem()
9. setdefault()
10. update()
11. values()
d) Define with syntax 'return' statement in Python. 2M
Ans. A return statement is used to end the execution of the function call and it "returns" Definition
the value of the expression following the return keyword to the caller. The = 1M,
statements after the return statements are not executed. If the return statement is Syntax = 1M
without any expression, then the special value None is returned.
OR
The return statement in Python terminates the execution of a function and returns a
value to the caller.
Syntax:
return [expression]
• return: Keyword that exits the function and optionally returns a value.
• expression: Optional value or expression to be returned. If omitted, the
function returns None by default.
e) State the used of comments in Python and enlist its types. 2M
Ans. Note: Considering the given question as State the use of comments in Python Use = 1M
and enlist its types. Any two types
½M each
Use of Comments:
Comments in Python are the lines in the code that are ignored by the
Page 2 of 32
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
Summer - 2025 EXAMINATION
Model Answer – Only for the Use of RAC Assessors
Subject Name: Programming With Python Subject Code: 22616
___________________________________________________________________________________________________________________
Q. Sub
Answer
XXXX
Marking
No. Q. N. Scheme
X
interpreter during the execution of the program.
• Comments enhance the readability of the code.
• Comment can be used to identify functionality or structure the code-base.
• Comment can help understanding unusual or tricky scenarios handled by the
code to prevent accidental removal or changes.
• Comments can be used to prevent executing any specific part of your code,
while making changes or testing.
Types of Comment:
1. Single Line Comment
2. Multiline Comment
3. Docstring Comments
Page 3 of 32
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
Summer - 2025 EXAMINATION
Model Answer – Only for the Use of RAC Assessors
Subject Name: Programming With Python Subject Code: 22616
___________________________________________________________________________________________________________________
Q. Sub
Answer
XXXX
Marking
No. Q. N. Scheme
X
3. The write() method 3.The writelines() method does not
returns the number of return the number of characters written
characters written on to the in the file.
file.
4.Syntax: file.write(byte) 4. Syntax : file.writelines(list)
Example:
my_list = [1, 2, 3]
my_list.append(4)
print(my_list)
# Output: [1, 2, 3, 4]
2. extend(): Adds multiple elements from an iterable to the end of the list.
my_list = [1, 2, 3]
my_list.extend([4, 5, 6])
print(my_list)
# Output: [1, 2, 3, 4, 5, 6]
my_list = [1, 2, 3]
my_list.extend("abc") # Can also extend with strings
print(my_list)
# Output: [1, 2, 3, 'a', 'b', 'c']
Page 4 of 32
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
Summer - 2025 EXAMINATION
Model Answer – Only for the Use of RAC Assessors
Subject Name: Programming With Python Subject Code: 22616
___________________________________________________________________________________________________________________
Q. Sub
Answer
XXXX
Marking
No. Q. N. Scheme
X
3. insert(): Inserts an element at a specified index.
my_list = [1, 2, 3]
my_list.insert(1, "hello") # Insert "hello" at index 1
print(my_list)
# Output: [1, 'hello', 2, 3]
Page 5 of 32
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
Summer - 2025 EXAMINATION
Model Answer – Only for the Use of RAC Assessors
Subject Name: Programming With Python Subject Code: 22616
___________________________________________________________________________________________________________________
Q. Sub
Answer
XXXX
Marking
No. Q. N. Scheme
X
Write a Python function that takes a number as a parameter and check the
c) 4M
number is prime number or not.
Ans. User Defined function: Any relevant
logic = 4M
def is_prime(n):
if n <= 1:
return False
factors = 0
for i in range(1, n + 1):
if n % i == 0:
factors += 1
if factors > 2:
return False
return True
# Example usage
number = int(input("Enter a number: "))
if is_prime(number):
print(number ,"is a prime number.")
else:
print(number ,"is not a prime number.")
OR
Built in function
from sympy import *
g1 = isprime(4)
g2 = isprime(5)
print(g1)
Page 6 of 32
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
Summer - 2025 EXAMINATION
Model Answer – Only for the Use of RAC Assessors
Subject Name: Programming With Python Subject Code: 22616
___________________________________________________________________________________________________________________
Q. Sub
Answer
XXXX
Marking
No. Q. N. Scheme
X
print(g2)
Example :
e1 = Employee()
In this example, the Employee class has a default constructor __init__. When e1
object is created, the constructor is called and initialize with default values for name
and age.
Page 7 of 32
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
Summer - 2025 EXAMINATION
Model Answer – Only for the Use of RAC Assessors
Subject Name: Programming With Python Subject Code: 22616
___________________________________________________________________________________________________________________
Q. Sub
Answer
XXXX
Marking
No. Q. N. Scheme
X
OR
e1 = Employee("A", 19)
In this example, the Employee class has a parametrized constructor __init__ with
name and age arguments. When e1 object is created with parameters A and 19, the
constructor is called and initialize with give values for name and age.
Page 8 of 32
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
Summer - 2025 EXAMINATION
Model Answer – Only for the Use of RAC Assessors
Subject Name: Programming With Python Subject Code: 22616
___________________________________________________________________________________________________________________
Q. Sub
Answer
XXXX
Marking
No. Q. N. Scheme
X
num = float(input("Enter a number: "))
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")
OR
Using Function:
def check(n):
# if the number is positive
if n > 0:
print("Positive")
Page 9 of 32
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
Summer - 2025 EXAMINATION
Model Answer – Only for the Use of RAC Assessors
Subject Name: Programming With Python Subject Code: 22616
___________________________________________________________________________________________________________________
Q. Sub
Answer
XXXX
Marking
No. Q. N. Scheme
X
Note: Any relevant program shall be considered.
Write a program to print the number in words using list. Like 1234 => One,
b) 4M
Two, Three, Four etc.
Ans. # Function to return the word of the corresponding digit: Correct Logic
= 3M
def printValue(digit): &
Display output
# Switch block to check for each digit c
= 1M
# For digit 0
if digit == '0':
print("Zero ", end = " ")
# For digit 1
elif digit == '1':
print("One ", end = " ")
# For digit 2
elif digit == '2':
print("Two ", end = " ")
#For digit 3
elif digit=='3':
print("Three",end=" ")
# For digit 4
elif digit == '4':
print("Four ", end = " ")
# For digit 5
elif digit == '5':
print("Five ", end = " ")
# For digit 6
Page 10 of 32
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
Summer - 2025 EXAMINATION
Model Answer – Only for the Use of RAC Assessors
Subject Name: Programming With Python Subject Code: 22616
___________________________________________________________________________________________________________________
Q. Sub
Answer
XXXX
Marking
No. Q. N. Scheme
X
elif digit == '6':
print("Six ", end = " ")
# For digit 7
elif digit == '7':
print("Seven", end = " ")
# For digit 8
elif digit == '8':
print("Eight", end = " ")
# For digit 9
elif digit == '9':
print("Nine ", end = " ")
# Function to iterate through every digit in the given number
def printWord(N):
i=0
length = len(N)
# Finding each digit of the number
while i < length:
# Print the digit in words
printValue(N[i])
i += 1
# Driver code
N = "1234"
printWord(N)
OR
Page 11 of 32
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
Summer - 2025 EXAMINATION
Model Answer – Only for the Use of RAC Assessors
Subject Name: Programming With Python Subject Code: 22616
___________________________________________________________________________________________________________________
Q. Sub
Answer
XXXX
Marking
No. Q. N. Scheme
X
a=('zero','One','Two','Three','Four','five','six','seven','eight','nine')
b=[]
n=int(input("Enter any number"))
while n>0:
r=a[n%10]
n=n//10
b.append(r)
b.reverse()
print(b)
Note: Any relevant program shall be considered.
Syntax:
Parameters:
Page 12 of 32
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
Summer - 2025 EXAMINATION
Model Answer – Only for the Use of RAC Assessors
Subject Name: Programming With Python Subject Code: 22616
___________________________________________________________________________________________________________________
Q. Sub
Answer
XXXX
Marking
No. Q. N. Scheme
X
• source: A path-like object representing the file system path. This is the
source file path which is to be renamed.
Return Type:
Example:
import os
print("renaming done")
Deleting a directory:
Syntax:
OR
Syntax:
Page 13 of 32
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
Summer - 2025 EXAMINATION
Model Answer – Only for the Use of RAC Assessors
Subject Name: Programming With Python Subject Code: 22616
___________________________________________________________________________________________________________________
Q. Sub
Answer
XXXX
Marking
No. Q. N. Scheme
X
Example:
import os
os.rmdir("ABC") #ABC is empty directory
print("removing done")
OR
import shutil
shutil.rmtree("ABC") #ABC is not empty directory
print("removing done")
Note: Any relevant explanation and example shall be considered.
Write a program for importing module for addition and subtraction of two 4M
d)
numbers.
Ans. Creating a module called "Arithmetic_op.py" to perform addition and Creating
subtraction of two numbers: module = 2M,
Importing
# Arithmetic_op.py module = 1M
with correct
def add(x, y): syntax,
return x + y Calling
Functions = 1M
def subtract(x, y): OR
return x – y Importing
module = 2M,
Importing and Using the Module:
Calling
# main.py Functions = 2M
import Arithmetic_op
result_add = Arithmetic_op.add(5, 3)
result_subtract = Arithmetic_op.subtract(5, 3)
Page 14 of 32
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
Summer - 2025 EXAMINATION
Model Answer – Only for the Use of RAC Assessors
Subject Name: Programming With Python Subject Code: 22616
___________________________________________________________________________________________________________________
Q. Sub
Answer
XXXX
Marking
No. Q. N. Scheme
X
print("Addition:", result_add)
print("Subtraction:", result_subtract)
OR
print("Addition=",operator.add(10,20))
print("Subtraction=",operator.sub(20,10))
Q. Sub
Answer
XXXX
Marking
No. Q. N. Scheme
X
5. An identifier can be of any length.
3. Integral Types:
Python interprets a sequence of decimal digits without any prefix to be a
decimal number.
Q. Sub
Answer
XXXX
Marking
No. Q. N. Scheme
X
integer may be appended to specify scientific notation:
5. Complex numbers:
Complex numbers are specified as: real part + (imaginary part) j.
Example: 2+3j
6. Strings:
Strings are sequences of character data.
1. ‘within single quotes’.
2. “within double quotes”.
• A string in Python can contain as many characters as we wish.
• The only limit is our machine’s memory resources.
• A string can also be empty:
• Use the escape \ sequence if you want to include a quote character as
part of the string itself.
7. Decision Making:
• if, if else, if-elif-else, Nested if statements are used whenever we
want to make a decision based on some conditions.
• The syntax for decision making is, the line ends with: either after else
or after the condition is mentioned in the if block.
• The segment of code which needs to be executed as part of the
decision is written with indentation.
if statements:
• If the condition given in if block are true then, first only the code
written with indentation are executed and then the remaining code
will execute.
• If the condition is false then the code written in if block is skipped
and remaining code will be executed.
• Syntax: if condition: statement 1 statement 2
• Example:
a=20
if(a>10):
print('Inside if block')
print('a is bigger than 10')
print('After if statement')
if else statements:
if...else statements are used when we want to make any one decision out of
two based on some condition. If the condition is true the code in the if block
will be executed. If the condition is false then else block will be executed.
Page 17 of 32
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
Summer - 2025 EXAMINATION
Model Answer – Only for the Use of RAC Assessors
Subject Name: Programming With Python Subject Code: 22616
___________________________________________________________________________________________________________________
Q. Sub
Answer
XXXX
Marking
No. Q. N. Scheme
X
Once, any one of the code block (either if or else) is executed, the remaining
code wil be executed.
Syntax: if condition : statement 1 statement 2 else : statement 3 statement 4
nested if:
Python supports nested structures. Which means we can have if statement
inside another if statement.
Syntax :if condition 1 : statement 1 statement 2 if condition 2 : statement 3
else: statement 4 else: statement 5.
8. Loops in Python:
If there is any need to execute a set of instructions several times as long as
certain condition is true, we use looping structures such as for loops, while
loops, and nested loops.
for loops
It has the ability to iterate over the items of any sequence, such as a list or a
string.
for iterating_var in sequence: statements(s)
while loop
While loop is executed as long as the condition is true.
range( )
range ( ) is a built-in function of Python. It is used when a user needs to
perform
an action for a specific number of times.
Syntax: range(start, stop, step) Here start and step are optional. 0 will be
considered as start value and 1 as the step value in case if they are
not provided by the programmer.
Page 18 of 32
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
Summer - 2025 EXAMINATION
Model Answer – Only for the Use of RAC Assessors
Subject Name: Programming With Python Subject Code: 22616
___________________________________________________________________________________________________________________
Q. Sub
Answer
XXXX
Marking
No. Q. N. Scheme
X
9. Control Statements:
break
• break is used to control the sequence of the loop.
• If we want to terminate a loop and skip to the next code after the loop
then we use break statement.
• And if we want to continue in the loop in such case we use continue
statement.
• pass statement are null statements which are ignored by the
compilers.
• Usually, we use pass statements as placeholder.
4M
b) Write a program to take limit from user and print a fibonnacci series.
Ans. # Program to display the Fibonacci sequence up to n-th term using while loop Limit from user
= 1M
n = int(input("Enter the limit")) &
Correct logic
a=0
for printing
b=1 Fibonacci series
= 3M
next = b
count = 1
while count <= n:
print(next, end=" ")
count += 1
a, b = b, next
next = a + b
print( )
OR
# Program to display the Fibonacci sequence up to n-th term using while loop
nterms = int(input("How many terms? "))
# first two terms
Page 19 of 32
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
Summer - 2025 EXAMINATION
Model Answer – Only for the Use of RAC Assessors
Subject Name: Programming With Python Subject Code: 22616
___________________________________________________________________________________________________________________
Q. Sub
Answer
XXXX
Marking
No. Q. N. Scheme
X
n1, n2 = 0, 1
count = 0
# check if the number of terms is valid
if nterms <= 0:
print("Please enter a positive integer")
# if there is only one term, return n1
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
# generate fibonacci sequence
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1
Note: Any relevant logic/program shall be considered.
Page 20 of 32
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
Summer - 2025 EXAMINATION
Model Answer – Only for the Use of RAC Assessors
Subject Name: Programming With Python Subject Code: 22616
___________________________________________________________________________________________________________________
Q. Sub
Answer
XXXX
Marking
No. Q. N. Scheme
X
are defined. = 1M
• Local variables are created when the function starts executing and is &
destroyed when the execution is complete. Explanation of
• Local variables are more reliable and secure since the value cannot be Global Variable
changed by other functions. = 1M,
Example of
Global Variable: Global Variable
• Python Global variables are those which are not defined inside any function = 1M
and have a global scope.
• These variables are declared outside any function or class.
• These variables can be accessed from anywhere in the program.
• Global variables remain in existence for the entire time the program is
executing.
• Global variables are accessible by multiple functions, therefore its value can
be changed.
Example:
var1 =10 #global variable
def method1():
print("inside method")
var2 =20 #local variable
print(var1,"is accessible")
print(var2,"is accessible")
method1()
print("outside method")
print(var1,"is accessible")
print(var2,"is accessible")# throw an error because var2 is local
Note: Any Relevant explanation and example shall be considered.
Create a class employee with data members name, department and salary.
d) 4M
Create suitable methods to accept and print employee information.
Ans. # employee class code in Python class definition Defining a class
class Employee: with given data
__name="" members = 2M
__dept="" &
__salary=0 accepting and
printing
# function to set data employee
def setData(self,name,dept,salary): information
self.__name = name using suitable
Page 21 of 32
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
Summer - 2025 EXAMINATION
Model Answer – Only for the Use of RAC Assessors
Subject Name: Programming With Python Subject Code: 22616
___________________________________________________________________________________________________________________
Q. Sub
Answer
XXXX
Marking
No. Q. N. Scheme
X
self.__dept = dept methods
self.__salary = salary = 2M
emp=Employee()
emp.setData('ABC','Purchase',55000)
emp.showData()
OR
Getting values from the function:
class Employee:
__name=""
__dept=""
__salary=0
def setData(self):
self.__name = input("Enter Name:\t")
self.__dept = input("Enter Dept:\t")
self.__salary = int(input("Enter Salary:\t"))
def showData(self):
print("Name\t:", self.__name)
print("Dept\t:", self.__dept)
print("Salary\t:", self.__salary)
emp=Employee()
emp.setData('ABC','Purchase',55000)
emp.showData()
Q. Sub
Answer
XXXX
Marking
No. Q. N. Scheme
X
Each mode determines how the file will be opened and what operations are allowed.
Commonly used file modes are:
1. Read Mode (‘r’):
Example:
file = open(‘file.txt’, ‘r’)
content = file.read( )
print(content)
file.close( )
2. Write Mode (‘w’):
Example:
file = open(‘file.txt’, ‘w’)
file.write(“Hello, World!\n”)
file.write(“This is a new line.”)
file.close( )
3. Append Mode (‘a’):
Example:
Page 23 of 32
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
Summer - 2025 EXAMINATION
Model Answer – Only for the Use of RAC Assessors
Subject Name: Programming With Python Subject Code: 22616
___________________________________________________________________________________________________________________
Q. Sub
Answer
XXXX
Marking
No. Q. N. Scheme
X
• This mode is used for working with binary files, such as images,
audio files, etc.
• It’s often combined with read (`’rb’`) or write (‘wb’) modes.
• This mode is similar to ‘r+’, but it also truncates the file, removing its
existing contents.
Example:
Q. Sub
Answer
XXXX
Marking
No. Q. N. Scheme
X
@dispatch(int) class,
def area(self,side):
a=side*side 2M for correct
print("area of squre=",a) logic for
@dispatch(int,int) function
def area(self,length,breadth): definition of
a=length*breadth square,
print("area of rectangle",a)
2M for correct
logic for
s=Shape()
function
s.area(10) #calls area method of square
definition of
s.area(10,20) #calls area method of rectangle
rectangle,
Note: Any relevant logic/program shall be considered. 1M for function
calling with
different no of
parameters
c) 6M
Explain any two looping statements with syntax in Python with example.
Page 25 of 32
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
Summer - 2025 EXAMINATION
Model Answer – Only for the Use of RAC Assessors
Subject Name: Programming With Python Subject Code: 22616
___________________________________________________________________________________________________________________
Q. Sub
Answer
XXXX
Marking
No. Q. N. Scheme
X
Ans. Python primarily supports two types of loops - for loops and while loops. These can for loop:
be further enhanced with control statements and can be nested to handle more Explanation
complex scenarios. =1M,
Syntax = 1M,
For Loops example=1M
while loop:
The for loop in Python is designed to iterate over sequences such as lists, tuples,
Explanation
dictionaries, sets, or strings. Unlike for loops in many other programming languages,
=1M
Python's for loop functions more like an iterator method.
Syntax =1M
Syntax: Example = 1M
Page 26 of 32
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
Summer - 2025 EXAMINATION
Model Answer – Only for the Use of RAC Assessors
Subject Name: Programming With Python Subject Code: 22616
___________________________________________________________________________________________________________________
Q. Sub
Answer
XXXX
Marking
No. Q. N. Scheme
X
While Loops
The while loop executes a block of code as long as a specified condition is True.
Syntax:
while condition:
# code block to be executed
Examples:
Basic while loop:
number = 1
while number <= 3:
print(number)
number = number + 1
User input loop:
number = int(input('Enter a number: '))
while number != 0:
print(f'You entered {number}.')
number = int(input('Enter a number: '))
print('The end.')
This loop continues until the user enters 0
Page 27 of 32
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
Summer - 2025 EXAMINATION
Model Answer – Only for the Use of RAC Assessors
Subject Name: Programming With Python Subject Code: 22616
___________________________________________________________________________________________________________________
Q. Sub
Answer
XXXX
Marking
No. Q. N. Scheme
X
Ans. Steps to Create a Package in Python
1. Create a directory (folder) for the package. 2M for steps to
2. Inside that folder, create an empty file named __init__.py. (Marks the create package
directory as a package) in python,
3. Create a module (e.g., area_module.py) inside the package folder.
4. Write your class and method in the module. 2M for Create a
5. In another Python script, import the package and use the class/method. package for
rectangle,
Directory Structure
rectangle_package/ 2M for Import
│ package in
├── __init__.py another Python
├── area_module.py program to
main_program.py calculate area
of rectangle
Step 1: rectangle_package/area_module.py
# area_module.py
class Rectangle:
def area(self, length, breadth):
return length * breadth
Step 2: rectangle_package/__init__.py
# __init__.py
# (Can be empty or used to import modules)
from .area_module import Rectangle
Step 3: main_program.py (outside the package folder)
# main_program.py
from rectangle_package import Rectangle
# Create object
rect = Rectangle()
# Input
length = float(input("Enter length of rectangle: "))
breadth = float(input("Enter breadth of rectangle: "))
# Calculate and display area
print("Area of Rectangle =", rect.area(length, breadth))
b) Write a program that accept name and salary. Create a user defined exception 6M
‘Negative salary’, if salary is negative.
Ans. # Define user-defined exception 2M for defining
user defined
class NegativeSalaryError(Exception): Exception,
def __init__(self, salary): 2M for Accept
Page 28 of 32
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
Summer - 2025 EXAMINATION
Model Answer – Only for the Use of RAC Assessors
Subject Name: Programming With Python Subject Code: 22616
___________________________________________________________________________________________________________________
Q. Sub
Answer
XXXX
Marking
No. Q. N. Scheme
X
super().__init__(f"Error: Salary cannot be negative. You entered: {salary}") name and
salary
OR
&
class NegativeSalaryError(Exception):
2M for Correct
pass Logic to raise
Negative Salary
Error
# Main program
try:
name = input("Enter your name: ")
salary = float(input("Enter your salary: "))
if salary < 0:
raise NegativeSalaryError(salary)
print(f"Name: {name}")
print(f"Salary: {salary}")
except NegativeSalaryError as e:
print(e)
except ValueError:
print("Invalid input! Please enter a numeric value for salary.")
c) What is dictionary? State the use of dictionary in python and explain ways of
6M
adding and deleting elements from dictionary.
Ans. Definition of dictionary 1M for Correct
definition,
A dictionary in Python is a built-in data structure that stores data as key-value
pairs, where each key maps to a corresponding value. These pairs are enclosed in ½ M each for
curly braces {}, with keys and values separated by colons: any 2 uses of
dictionary,
Dictionaries are:
• Ordered (as of Python 3.7), meaning items retain their insertion order. Method to add
=1M each (Any
• Mutable, allowing modifications after creation. Two)
Page 29 of 32
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
Summer - 2025 EXAMINATION
Model Answer – Only for the Use of RAC Assessors
Subject Name: Programming With Python Subject Code: 22616
___________________________________________________________________________________________________________________
Q. Sub
Answer
XXXX
Marking
No. Q. N. Scheme
X
• Unique-keyed, prohibiting duplicate keys (later assignments overwrite
earlier ones). Method to
delete
• Efficient, using hash tables for rapid key-based lookups. = 1M each
(Any Two)
Primary Uses in Python Programming
Dictionaries serve critical roles in software development due to their flexibility and
performance:
1. Data Aggregation
Group related attributes (e.g., user profiles, product details).
2. Configuration Management
Store application settings and environment variables.
3. JSON/API Handling
Naturally represent JSON data structures for web applications.
4. Caching/Memorization
Accelerate function calls by caching results using input parameters as keys.
5. Dynamic Data Storage
Manage evolving datasets where fixed indexes are impractical.
Adding Elements to Dictionaries
student= { }
1. Direct Assignment
Add or update items using square bracket notation:
student["GPA"] = 3.8 # Adds new key
student["age"] = 22 # Updates existing key
• Overwrites existing keys.
• O(1) time complexity for insertions.
2. update( ) Method
Merge multiple items from another dictionary/inerrable:
student.update({
Page 30 of 32
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
Summer - 2025 EXAMINATION
Model Answer – Only for the Use of RAC Assessors
Subject Name: Programming With Python Subject Code: 22616
___________________________________________________________________________________________________________________
Q. Sub
Answer
XXXX
Marking
No. Q. N. Scheme
X
"department": "Computer Science",
"scholarship": True
})
• Adds new items and updates existing ones
• Ideal for bulk operations
3. setdefault( )
Safely add keys with default values:
student.setdefault("attendance", 95) # Adds if missing
• Returns existing value if key exists
• Prevents accidental overwrites
4. Dictionary Comprehension
Create/modify dictionaries programmatically:
grades = {course: 90 for course in student["courses"]}
• Generates new dictionaries from iterables
Removing Elements from Dictionaries
1. del Statement
Permanently delete by key:
del student["courses"] # Removes 'courses' entry
• Raises KeyError for nonexistent keys
• Direct memory deallocation
2. pop( )
Remove and return a key's value:
age = student.pop("age") # Returns 22
• Optional default return for missing keys
Page 31 of 32
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
Summer - 2025 EXAMINATION
Model Answer – Only for the Use of RAC Assessors
Subject Name: Programming With Python Subject Code: 22616
___________________________________________________________________________________________________________________
Q. Sub
Answer
XXXX
Marking
No. Q. N. Scheme
X
• Safe for conditional removal
3. popitem( )
Remove and return last inserted item (Python 3.7+):
key, value = student.popitem() # Removes last added pair
• Useful for LIFO processing
• Efficient for destructive iteration
4. clear( )
Reset dictionary by removing all items:
student.clear( ) # Empty dictionary: {}
• Retains dictionary object
• O(1) time complexity
Page 32 of 32