0% found this document useful (0 votes)
15 views32 pages

XXXX X: Important Instructions To Examiners

The document is a model answer sheet for the Summer 2025 examination on Programming with Python, provided by the Maharashtra State Board of Technical Education. It includes important instructions for examiners on assessing candidates' answers, along with a series of questions and model answers covering various Python programming concepts. Topics include the characteristics of Python, list manipulation, variable declaration rules, and the use of constructors.

Uploaded by

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

XXXX X: Important Instructions To Examiners

The document is a model answer sheet for the Summer 2025 examination on Programming with Python, provided by the Maharashtra State Board of Technical Education. It includes important instructions for examiners on assessing candidates' answers, along with a series of questions and model answers covering various Python programming concepts. Topics include the characteristics of Python, list manipulation, variable declaration rules, and the use of constructors.

Uploaded by

narvekarmahin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 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
___________________________________________________________________________________________________________________

Important Instructions to examiners: XXXX


1) The answers should be examined by key words and not as word-to-word as given in the model answer
scheme. X
2) The model answer and the answer written by candidate may vary but the examiner may try to assess the
understanding level of the candidate.
3) The language errors such as grammatical, spelling errors should not be given more Importance (Not
applicable for subject English and Communication Skills.
4) While assessing figures, examiner may give credit for principal components indicated in the figure. The
figures drawn by candidate and model answer may vary. The examiner may give credit for any equivalent
figure drawn.
5) Credits may be given step wise for numerical problems. In some cases, the assumed constant values may
vary and there may be some difference in the candidate’s answers and model answer.
6) In case of some questions credit may be given by judgement on part of examiner of relevant answer based
on candidate’s understanding.
7) For programming language papers, credit may be given to any other program based on equivalent concept.
8) As per the policy decision of Maharashtra State Government, teaching in English/Marathi and Bilingual
(English + Marathi) medium is introduced at first year of AICTE diploma Programme from academic year
2021-2022. Hence if the students write answers in Marathi or bilingual language (English +Marathi), the
Examiner shall consider the same and assess the answer based on matching of concepts with model
answer.

Q. Sub Marking
Answer
No. Q. N. Scheme

1. Attempt any FIVE of the following: 10 M

a) Why Python is called as interpreted and platform independent language? 2M

Ans. Interpreted: Interpreted


Python is called an interpreted language because it executes code logic directly, line =1M
by line, without the need for a separate compilation step. In methods to compiled Platform
languages like C or C++, where the source code is translated into machine code independent
before execution, Python code is translated into intermediate code by the Python = 1M
interpreter.
Platform independent:
Python's platform independence means you can write a Python script on one
operating system (like Windows) and run it on another (like Linux) without needing
to modify the code. This is because Python code is first compiled to bytecode, an
intermediate language, which is then interpreted by the PVM.

b) State the use of 'else' in for loop. 2M


Ans. The else clause in a Python for loop executes after the loop completes normally, 2M
meaning it was not terminated by a break statement. It provides a way to run specific
code only when the loop finishes all its iterations without interruption. This is useful

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

f) State the use of inheritance. 2M


Ans. Use of Inheritance in Python is a mechanism in which one class acquires the Correct use
attributes and methods of another class. It promotes code reusability, reduces = 2M
redundancy, and establishes a clear hierarchy between classes.
OR
OR Any two uses
1. Code reusability = 1M each
2. Reduces redundancy
3. Establishes a clear hierarchy between classes
4. Extensibility
5. Polymorphism
6. Multiple Inheritance
7. Method Overriding
g) State any two difference between write and writelines methods. 2M
Ans. Any two
write() writelines() differences
1. The write() method is 1.The writelines() method is used to = 1M each
used to write a single string write multiple strings to a file.
to a file.
2. The write() method takes 2.The writelines() method takes an
a string as an argument. iterable object like lists, tuple, etc.
containing strings as an argument.

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)

2. Attempt any THREE of the following: 12M

a) Explain with example how to add elements to a list. 4M


Ans. To add elements to a list in Python, you can use the append(), extend(), Explanation
and insert() methods, as well as the + operator for concatenation. =½M
&
The append() method adds a single element to the end of the list, extend() adds Example
multiple elements (from an iterable) to the end, insert() adds an element at a specific = ½ M each
index, and the + operator combines two lists into a new one. (4 methods)

Example:

1. append( ): Adds an element to the end of the list.

my_list = [1, 2, 3]
my_list.append(4)
print(my_list)
# Output: [1, 2, 3, 4]

Here my_list.append(4) adds 4 to the end of the list.

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]

4.+ operator (concatenation): Creates a new list by combining two lists.


list1 = [1, 2, 3]
list2 = [4, 5, 6]
new_list = list1 + list2
print(new_list)
# Output: [1, 2, 3, 4, 5, 6]

b) What is variable? State rule for variable declaration in Python. 4M


Ans. Definition of Variable: Definition = 1M
● Variable is a name given to memory location. Rules = 1M
● Variables are used to store data, they take memory space based on the each (any three)
type of value assigned to them.
● Creating variables in Python is simple, just write the variable name on the
left side of = and the value on the right side.
● Unlike C programming python has not demand for variable declaration.
● Variable gets created when you assign value to variable.
● Example :
x=5
y = ‘hello’

Rules for declaring variables in Python:


1. A variable name must start with a letter (A-Z, a-z) or an underscore (_).
2. It can contain letters, numbers (0-9), and underscores.
3. It cannot start with a number.
4. Variable names are case-sensitive (e.g., myVar and myvar are different
variables).
5. It cannot be a reserved keyword in Python
(e.g., if, else, for, while, def, class, import, True, False, None).
6. Special characters like !, @, #, $, %, etc are not allowed.

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)

d) What is constructor? How to implement it in Python? Explain with example. 4M


Ans. Definition of Constructor: Definition
A constructor is a special method used to initialize objects of a class. = 1M,
In Python, the constructor is named __init__. It is automatically called when an Implementation
object is created for class, allowing you to set initial values for the object's attributes. =1M
&
Implementation of Constructor: Example with
• The __init__ method is the most common constructor in Python used to explanation
initialize class attributes. = 2M
• Every class in Python has a constructor even if it relies on the default
constructor.
• The __init__ method takes the self keyword as the first argument, allowing
access to methods of the class.
Syntax
class ClassName:
def __init__(self, parameter1, parameter2, ...):
# Constructor code here

Example :

Default Constructor Example:


class Employee:
'Common base class for all employees'
def __init__(self):
self.name = "XYZ"
self.age = 20

e1 = Employee()

print ("Name: ",e1.name)


print ("age: ",e1.age)

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

Parameterized Constructor Example:


class Employee:
'Common base class for all employees'
def __init__(self, name, age):
self.name = name
self.age = age

e1 = Employee("A", 19)

print ("Name: ",e1.name)


print ("age: ",e1.age)

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.

3. Attempt any THREE of the following: 12M

a) Write a program to check if a number is Positive, Negative or Zero. 4M


Ans. # Python program to check whether the number is positive, negative or equal to Correct Logic
zero = 3M
&
Without Function: Display output
=1M
num = float (input ("Enter a number: "))
if num > 0:
print ("Positive number")
elif num == 0:
print("Zero")
else:
print ("Negative number")
OR

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")

# if the number is negative


elif n < 0:
print("Negative")

# if the number is equal to zero


else:
print("Equal to zero")
number=int(input("Enter the number to check"))
check(number)

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.

c) Explain with example how to rename and delete directory in Python. 4M


Ans. Renaming Directory: Explanation of
Renaming
• OS module in Python provides functions for interacting with the operating directory =1M
system. &
• OS comes under Python’s standard utility modules. Example =1M,
• This module provides a portable way of using operating system-dependent
functionality. Explanation of
• To rename a file or directory in Python you can use os.rename() function of Deleting
OS module. directory =1M
• This method renames a source file or directory to a specified destination file &
or directory. Example =1M
• It takes two parameters - source (current file name) and destination (new file
name).

Syntax:

os.rename(source, destination, *, src_dir_fd = None, dst_dir_fd = None)

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.

• destination: A path-like object representing the file system path.

• src_dir_fd (optional): A file descriptor referring to a directory.

• dst_dir_fd (optional): A file descriptor referring to a directory.

Return Type:

This method does not return any value.

Example:

# Python program to explain os.rename() method

import os

os.rename("ABC","XYZ") #ABC is directory

print("renaming done")

Deleting a directory:

os.rmdir() method in Python is used to remove or delete an empty directory.

OSError will be raised if the specified path is not an empty directory.

Syntax:

os.rmdir(path, *, dir_fd = None)

OR

shutil.rmtree() is used to delete an entire directory tree, path must point to a


directory.

Syntax:

shutil.rmtree(path, ignore_errors=False, onerror=None)

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

# Perform operations using the functions from the module

result_add = Arithmetic_op.add(5, 3)

result_subtract = Arithmetic_op.subtract(5, 3)

# Print the results

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

import operator #using built in operator module

print("Addition=",operator.add(10,20))

print("Subtraction=",operator.sub(20,10))

Note: Any relevant program Shall be considered.


12M
4. Attempt any THREE of the following:
4M
a) Enlist and explain any two building blocks of Python.
Ans. Listing building blocks of Python: Listing building
1. Identifiers and Keywords blocks of
2. Integral Types Python,
3. Floating point types (½ M each)
4. Complex numbers = 1M,
5. Strings (Any 2)
6. Decision Making &
7. Loops in Python Explanation of
8. Control Statements building blocks
of python
Explanation: (1½ M each)
= 3M
1. Identifiers and Keywords: (Any 2)

1. Identifiers can be a combination of:


a. Lowercase (a to z)
b. Uppercase (A to Z)
c. Digits (0 to 9)
d. An underscore_

Examples: myClass, var_1, print_this_to_screen.


2. An identifier cannot start with a digit.
Example: 1variable is invalid, but variable1 is a valid.
3. Keywords cannot be used as identifiers.
4. We cannot use special symbols like !, @, #, $, % etc. in our identifier.
Page 15 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
5. An identifier can be of any length.

2. Python Keywords: Keywords are the reserved words in Python.


1. We cannot use a keyword as a variable name, function name or any other
identifier. They are used to define the syntax and structure of the Python
language.
2. There are 35 keywords in Python 3.7. This number can vary slightly over
the course of time.
3. In Python, keywords are case sensitive.
4. All the keywords except True, False and None are in lowercase and they
must be written as they are. The list of all the keywords is given below.

Table: Python Keywords

3. Integral Types:
Python interprets a sequence of decimal digits without any prefix to be a
decimal number.

4. Floating point types:


• The float type in Python designates a floating-point number.
• Float values are specified with a decimal point.
• Optionally, the character e or E followed by a positive or negative
Page 16 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
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

if elif else statements:


if else statements are used when we need to check two conditions but if there
are multiple conditions which needs to be checked then we use if elif
statements. Here, else block is optional. else block will be executed if none
of the if conditions are true.
Syntax: if condition 1 : statement 1 statement 2 elif condition 2 : statement 3
statement 4 elif condition 3 : statement 5 statement 6 .... .... .... 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.

Syntax : while condition : statement 1 statement 2 ...........

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.

c) Explain concept of local and global variable in Python with example. 4M


Ans. Local Variable: Explanation of
• Python local variables are those which are defined inside a function and their Local Variable
scope is limited to that function only. = 1M,
• Local variables are declared within a function or block of code. Example of
• Local variables are only accessible within the function or block where they Local Variable

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

# function to get/print data


def showData(self):
print("Name\t:", self.__name)
print("City\t:", self.__dept)
print("Salary\t:", self.__salary)

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()

Note: Any relevant logic/program shall be considered.

e) Explain different way of opening a file in Python. 4M


Ans. Different way of opening a file in Python: Explanation of
mode with
In Python, the ‘open()’ function accepts various modes for working with files. example =1 M
each (any four)
Page 22 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
Each mode determines how the file will be opened and what operations are allowed.
Commonly used file modes are:
1. Read Mode (‘r’):

• This is the default mode for opening files.


• It allows you to read the contents of a file.

Example:
file = open(‘file.txt’, ‘r’)
content = file.read( )
print(content)
file.close( )
2. Write Mode (‘w’):

• This mode opens a file for writing.


• If the file exists, its contents are overwritten.
• If it doesn’t exist, a new file is created.

Example:
file = open(‘file.txt’, ‘w’)
file.write(“Hello, World!\n”)
file.write(“This is a new line.”)
file.close( )
3. Append Mode (‘a’):

• This mode opens a file for appending new content.


• The new content is added to the end of the file.
• If the file doesn’t exist, a new file is created.

Example:

file = open(‘file.txt’, ‘a’)


file.write(“This line will be appended.\n”)
file.write(“So will this one.”)
file.close( )
4. Binary Mode (‘b’):

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.

Example (Reading a binary file):

file = open(‘image.jpg’, ‘rb’)


data = file.read( )
# Process the binary data
file.close( )
5. Read and Write Mode (‘r+’):

• This mode allows reading from and writing to a file.

• It doesn’t truncate the file, preserving its existing contents.


Example:

file = open(‘file.txt’, ‘r+’)


content = file.read( )
file.write(“This line is added in read and write mode.”)
file.close( )
6. Write and Read Mode (‘w+’):

• This mode is similar to ‘r+’, but it also truncates the file, removing its
existing contents.
Example:

file = open(‘file.txt’, ‘w+’)


file.write(“This line is added in write and read mode.”)
content = file.read( )
file.close( )

5. Attempt any TWO of the following: 12M


Write a program to create a class to print the area of a square and a rectangle.
a) The class has two methods with the same name but different number of 6M
parameters.
Ans. from multipledispatch import dispatch 1M for
Declaration of
class Shape:
Page 24 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
@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

Write programs on following questions of tuple –


Given t1= (10, 20, 50, 30, 50, 40)
b) 6M
i) Find the length of tuple.
ii) Check if an element exists in a tuple.
Ans. # Given tuple 3M for
Calculate length
t1 = (10, 20, 50, 30, 50, 40) of tuple,
# i) Find the length of tuple 3M for
checking if an
print("Length of the tuple:", len(t1))
element exists
# ii) Check if an element exists in a tuple in a tuple

element = 30 # You can change this to test with other values


if element in t1:
print(f"Element {element} exists in the tuple.")
else:
print(f"Element {element} does not exist in the tuple.")

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

for variable in sequence:


# code block to be executed
In this syntax, the variable temporarily holds the value of each item in
the sequence during each iteration.
Examples:
Iterating through a list:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Using range( ) function:
The range( ) function returns a sequence of numbers, which is often used with for
loops.
for x in range(1, 11):
print(x)
This will print numbers from 1 to 1013.
Iterating through a string:
language = 'Python'
for character in language:
print(character)

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

6. Attempt any TWO of the following: 12M


Enlist steps to create package in python and design a package containing the
a) class which define the method to find area of rectangle. Import it in another 6M
Python program to calculate area of rectangle.

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

You might also like