0% found this document useful (0 votes)
46 views24 pages

Win 24

This document is a model answer paper for the Winter 2024 examination on Programming with Python, intended for use by RAC assessors. It includes important instructions for examiners regarding assessment criteria and provides a series of questions along with model answers covering various Python programming concepts. The content includes topics such as Python features, membership operators, decision-making statements, list methods, and file handling modes.

Uploaded by

unnati.kale286
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)
46 views24 pages

Win 24

This document is a model answer paper for the Winter 2024 examination on Programming with Python, intended for use by RAC assessors. It includes important instructions for examiners regarding assessment criteria and provides a series of questions along with model answers covering various Python programming concepts. The content includes topics such as Python features, membership operators, decision-making statements, list methods, and file handling modes.

Uploaded by

unnati.kale286
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/ 24

lOMoARcPSD|49418476

22616 - Model answer paper

Computer (Shikshan Maharshi Dadasaheb Rawal Government Polytechnic, Dhule)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by Fevicol ([email protected])
lOMoARcPSD|49418476

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

WINTER – 2024 EXAMINATION


Model Answer – Only for the Use of RAC Assessors

Subject: Programming with Python Subject Code: 22616

Important Instructions to examiners:


1) The answers should be examined by key words and not as word-to-word as given
in the model answer scheme.
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 in first year (first and second semesters) 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 Answer Marking


No Q.N. Scheme
1. Attempt any FIVE of the following: 10M
a) List features of Python 2M
Ans.  Easy to Learn and Use Any four
features
 Interactive Mode ½M each
 Expressive Language
 Interpreted Language
 Cross-platform Language
 Portable
 Free and Open Source
 Object-Oriented Language
 Extensible
 Large Standard Library

Page 1 / 23

Downloaded by Fevicol ([email protected])


lOMoARcPSD|49418476

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

WINTER – 2024 EXAMINATION


Model Answer – Only for the Use of RAC Assessors

Subject: Programming with Python Subject Code: 22616

b) List membership operators in Python. 2M


Ans. Membership Operators: The membership operators in Python are Each
used to find the existence of a particular element in the sequence and operator 1M
used only with sequences like string, tuple, list, dictionary etc.

Sr. Operator Description Example


No
1 in True if value is >>> x="Hello World"
found in list or in >>> print('H' in x)
sequence, and false True
it item is not in list
or in sequence
2 not in True if value is not >>> x="Hello World"
found in list or in >>> print("Hello" not
sequence, and false in x) False
if item is in list or in
sequence.

c) Compare list and Tuple 2M


Ans. List Tuple
Lists are mutable Tuples are immutable Any two
correct
Lists consume more memory Tuple consume less memory as
differences
compared to the list 1M each
Lists have several built-in Tuple does not have many
methods built-in methods
The unexpected changes and In tuple, it is hard to take place
errors are more likely to occur
In tuple
The List has the variable The tuple has the fixed length
length
Lists can be used to store Tuples are used to store only
homogeneous and heterogeneous elements.
heterogeneous elements
List iteration is slower and is Tuple iteration is faster.
time consuming.

Page 2 / 23

Downloaded by Fevicol ([email protected])


lOMoARcPSD|49418476

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

WINTER – 2024 EXAMINATION


Model Answer – Only for the Use of RAC Assessors

Subject: Programming with Python Subject Code: 22616

d) List different object oriented features supported by Python 2M


Ans. The main object-oriented features supported by Python:- Listing any
 Classes four
features ½
 Objects M each
 Encapsulation
 Inheritance
 Polymorphism
 Abstraction
e) State how to perform comments in Python 2M
Ans. Single line comment: Single-line comments are created simply by Correct
beginning a line with the hash (#) character, and they are explanation
of each 1M
automatically terminated by the end of line.
Example:
# print is a statement print(„Hello Python‟)
Multi line comment: Python multi-line comment is a piece of text
enclosed in a delimiter (""") Triple quotation marks.
Example:
""" Multi-line comment used
print("Python Comments") """
or To add a multiline comment you could insert a # for each line:
Example:
#This is a comment
#written in
#more than just one line print("Hello, World!")
f) Define class and object 2M
Ans. Note: Any other relevant definition shall be considered Correct
Class: A class is a user-defined blueprint or prototype from which definition of
each 1M
objects are created. Classes provide a means of bundling data and
functionality together.
Object: An object is an instance of a class that has some attributes
and behavior. Objects can be used to access the attributes of the class.

g) List different modes of opening file in Python 2M


Ans. Modes for opening file: Any two
correct
• r: open an existing file for a read operation. modes 1M
• w: open an existing file for a write operation. If the file already each
contains some data then it will be overridden.

Page 3 / 23

Downloaded by Fevicol ([email protected])


lOMoARcPSD|49418476

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

WINTER – 2024 EXAMINATION


Model Answer – Only for the Use of RAC Assessors

Subject: Programming with Python Subject Code: 22616

• a: open an existing file for append operation. It won‟t override


existing data.
• r+: To read and write data into the file. The previous data in the file
will be overridden.
• w+: To write and read data. It will override existing data.
• a+: To append and read data from the file. It won‟t override existing
data.
2. Attempt any THREE of the following: 12M
a) Explain decision making statements if-else, if-elif-else with 4M
example. Explanation
Ans. Decision-making statements in Python allow the execution of specific of each
statement
blocks of code based on conditions. Python provides several with
constructs for decision-making example 2M

if-else Statement
The if-else statement is used to test a condition. If the condition is
True, the code inside the if block is executed. If the condition is
False, the code inside the else block is executed.

Syntax:
if condition:
# Code block to execute if the condition is True
else:
# Code block to execute if the condition is False
Example:
age = 16
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")

if-elif-else Statement
The if-elif-else statement is used when there are multiple conditions
to check. Python evaluates each if or elif condition in sequence. If
one of the conditions evaluates to True, the corresponding block of
code is executed, and the rest are skipped. If none of the if or elif
conditions are True, the code inside the else block is executed.

Page 4 / 23

Downloaded by Fevicol ([email protected])


lOMoARcPSD|49418476

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

WINTER – 2024 EXAMINATION


Model Answer – Only for the Use of RAC Assessors

Subject: Programming with Python Subject Code: 22616

Syntax:
if condition1:
# Code block to execute if condition1 is True
elif condition2:
# Code block to execute if condition1 is False and condition2 is
True
else:
# Code block to execute if both condition1 and condition2 are
False

Example:
age = 25
if age < 13:
print("You are a child.")
elif 13 <= age <= 19:
print("You are a teenager.")
elif 20 <= age <= 59:
print("You are an adult.")
else:
print("You are a senior.")

b) Describe any four methods of list in python. 4M


Ans. Four commonly used methods of lists in Python: Description
of each
1. append(): Adds a single item to the end of the list. method 1M
Syntax:
list.append(item)
Example:
fruits = ['apple', 'banana', 'cherry']
fruits.append('orange') # Adds 'orange' to the end of the list
print(fruits)

2. remove():Removes the first occurrence of a specified element


from the list.
Syntax:
list.remove(item)

Page 5 / 23

Downloaded by Fevicol ([email protected])


lOMoARcPSD|49418476

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

WINTER – 2024 EXAMINATION


Model Answer – Only for the Use of RAC Assessors

Subject: Programming with Python Subject Code: 22616

Example:
fruits = ['apple', 'banana', 'cherry', 'banana']
fruits.remove('banana') # Removes the first occurrence of 'banana'
print(fruits)

3. pop() : Removes and returns an item at a specified index from the


list. If no index is provided, it removes and returns the last item.
Syntax:
list.pop(index) # Removes and returns the item at the given index
list.pop() # Removes and returns the last item
Example:
fruits = ['apple', 'banana', 'cherry']
popped_item = fruits.pop(1) # Removes and returns the item at index
1
print(fruits) # List after removal
print(popped_item) # The removed item
4. sort() : Sorts the items of the list in ascending order (by default). It
can also sort in descending order by passing an argument to the
reverse parameter.
Syntax:
list.sort()
Example:
numbers = [5, 3, 8, 1, 2]
numbers.sort() # Sorts the list in ascending order
print(numbers)

c) Write a program illustrating use of user defined package in 4M


Python. 2M for
Ans. defining
A package is a hierarchical file directory structure that defines a package
single Python application environment that consists of modules and
2M for
subpackages and sub-subpackages, and so on. Packages allow for a
importing
hierarchical structuring of the module namespace using dot notation. package in
Creating a package is quite straightforward, since it makes use of the program
operating system‟s inherent hierarchical file structure.

Page 6 / 23

Downloaded by Fevicol ([email protected])


lOMoARcPSD|49418476

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

WINTER – 2024 EXAMINATION


Model Answer – Only for the Use of RAC Assessors

Subject: Programming with Python Subject Code: 22616

Consider the following arrangement:

Here, there is a directory named pkg that contains two modules,


mod1.py and mod2.py. The contents of the modules are:
mod1.py
def m1():
print("first module")
mod2.py
def m2():
print("second module")
If the pkg directory resides in a location where it can be found, you
can refer to the two modules with dot
notation(pkg.mod1, pkg.mod2) and import them with the syntax:
Syntax-1
import <module_name>[, <module_name> ...]
Example:
>>>import pkg.mod1, pkg.mod2
>>> pkg.mod1.m1()
first module
Syntax-2:
from <module_name> import <name(s)>
Example:
>>> from pkg.mod1 import m1
>>> m1()
first module
d) Describe various modes of file object? Explain any two in detail. 4M
Ans.  r': Read (default mode)
Description
 'w': Write (creates a new file or truncates an existing file)
of any four
 'x': Exclusive creation (fails if the file exists) modes 2M
 'a': Append (adds content to the end of the file)
 'b': Binary (used with other modes to handle binary files)

Page 7 / 23

Downloaded by Fevicol ([email protected])


lOMoARcPSD|49418476

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

WINTER – 2024 EXAMINATION


Model Answer – Only for the Use of RAC Assessors

Subject: Programming with Python Subject Code: 22616

 't': Text (default mode, used for text files)


 'r+': Read and Write (file must exist) Explanation
 'w+': Write and Read (creates a new file or truncates an of any two
existing file) 1M each
 'a+': Append and Read (adds content to the end of the file)

r' (Read Mode)


Opens the file for reading only. The file must already exist, and an
error (FileNotFoundError) will be raised if the file does not exist.
Example:
try:
file = open('example.txt', 'r') # Opens the file for reading
content = file.read() # Reads the entire content of the file
print(content)
except FileNotFoundError:
print("File not found!")
finally:
file.close() # Always close the file after use

'w' (Write Mode)


Opens the file for writing. If the file already exists, it overwrites the
file (erases its content). If the file does not exist, it is created.
Example:
with open('example.txt', 'w') as file: # Opens for writing, creates file
if it doesn't exist
file.write("Hello, World!") # Writes to the file
3. Attempt any THREE of the following: 12M
a) Explain identity and assignment operators with example 4M
Ans. Identity operators in Python are used to compare the memory 2M for
addresses of two objects, determining whether two variables or identity and
2M for
objects reference the same memory location. There are two primary assignment
identity operators in Python. operators

 1) is operator: Returns True if two variables refer to the same


memory location.

Page 8 / 23

Downloaded by Fevicol ([email protected])


lOMoARcPSD|49418476

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

WINTER – 2024 EXAMINATION


Model Answer – Only for the Use of RAC Assessors

Subject: Programming with Python Subject Code: 22616

 2) is not operator: Returns True if two variables do not refer to the


same memory location.

Example 1: Using the "is" Operator
x =[1,2,3]
y=x
result = x is y
print(result) # Output: True

Example 2: Using the "is not" Operator


a ="hello"
b ="world"
result = a is not b
print(result) # Output: True

Assignment Operators (Augmented Assignment Operators):


Assignment operators are used in Python programming to assign
values to variables. The assignment operator is used to store the value
on the right-hand side of the expression on the left-hand side variable
in the expression.
For example, a = 5 is a simple assignment operator that assigns the
value 5 on the right to the variable a on the left.
There are various compound operators in Python like a += 5 that adds
to the variable and later assigns the same. It is equivalent toa = a + 5.
Following are assignment operators in Python programming:
Operator Name Example
= Assignment Operator a = 7
+= Addition Assignment a += 1 # a = a + 1
-= Subtraction Assignment a -= 3 # a = a - 3
*= Multiplication Assignment a *= 4 # a = a * 4
/= Division Assignment a /= 3 # a = a / 3
%= Remainder Assignment a %= 10 # a = a % 10
**= Exponent Assignment a **= 10 # a = a ** 10

b) How to create dictionary in python? Write any three methods of 4M


dictionary.
Ans. Dictionary is an unordered collection of key-value pairs. It is the
same as the hash table type. The order of elements in a dictionary is
undefined, but we can iterate over the following:

Page 9 / 23

Downloaded by Fevicol ([email protected])


lOMoARcPSD|49418476

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

WINTER – 2024 EXAMINATION


Model Answer – Only for the Use of RAC Assessors

Subject: Programming with Python Subject Code: 22616

o The key 2M for


o The value dictionary
creation
o The items (key-value pairs) in a dictionary. syntax &
When we have the large amount of data, the dictionary datatype is example
used. Items in dictionaries are enclosed in curly braces{ } and
separated by the comma (,). A colon (:) is used to separate key from 2M for any
value. Values can be assigned and accessed using square braces ([]). 3 methods
Example: For dictionary data type.
>>> dic1={1:"First"," Second":2}
>>> dic1
{1: 'First', 'Second': 2}
>>> type(dic1)
<class 'dict'>
>>> dic1[3]="Third"
>>> dic1
{1: 'First', 'Second': 2, 3: 'Third'}
>>> dic1.keys()
dict_keys([1, 'Second', 3])
>>> dic1.values()
dict_values(['First', 2, 'Third'])
>>

Python has a set of built-in methods that we can use on dictionaries.

Method Description

clear() Removes all the elements from the dictionary

copy() Returns a copy of the dictionary

fromkeys() Returns a dictionary with the specified keys and


value

get() Returns the value of the specified key

Page 10 / 23

Downloaded by Fevicol ([email protected])


lOMoARcPSD|49418476

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

WINTER – 2024 EXAMINATION


Model Answer – Only for the Use of RAC Assessors

Subject: Programming with Python Subject Code: 22616

items() Returns a list containing a tuple for each key


value pair

pop() Removes the element with the specified key

popitem() Removes the last inserted key-value pair

setdefault() Returns the value of the specified key. If the


key does not exist: insert the key, with the
specified value

update() Updates the dictionary with the specified key-


value pairs

values() Returns a list of all the values in the dictionary

c) Explain how to use user defined function in python with example. 4M


Ans. • In Python, def keyword is used to declare user defined functions. Explanation
• The function name with parentheses (), which may or may not 2M
Example
include parameters and arguments and a colon: 2M
• An indented block of statements follows the function name and
arguments which contains the body of the function.
Syntax:
def function_name():
statements
.
.
Example:
def fun():
print(“User defined function”)
fun()
output:
User defined function
Parameterized function: The function may take arguments(s) also
called parameters as input within the opening and closing
parentheses, just after the function name followed by a colon.
Syntax:
def function_name(argument1, argument2, ...):

Page 11 / 23

Downloaded by Fevicol ([email protected])


lOMoARcPSD|49418476

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

WINTER – 2024 EXAMINATION


Model Answer – Only for the Use of RAC Assessors

Subject: Programming with Python Subject Code: 22616

Example:
def square( x ):
print("Square=",x*x)
# Driver code
square(2)
Output:
Square= 4

d) Describe the concept of inheritance in python with example. 4M


Ans. • In inheritance objects of one class procure the properties of objects 2M for
inheritance
of another class. explanation
• Inheritance provides code usability, which means that some of the
new features can be added to the code while using the existing code.
2M for
• The mechanism of designing or constructing classes from other example
classes is called inheritance.
• The new class is called derived class or child class and the class
from which this derived class has been inherited is the base class or
parent class.
• In inheritance, the child class acquires the properties and can access
all the data members and functions defined in the parent class. A
child class can also provide its specific implementation to the
functions of the parent class.
Syntax:
class A:
# properties of class A
class B(A):
# class B inheriting property of class A
# more properties of class B
Example 1: Inheritance without using constructor.
class Vehicle: #parent class
name="Maruti"
def display(self):
print("Name= ",self.name)
class Category(Vehicle): #derived class
price=2000

Page 12 / 23

Downloaded by Fevicol ([email protected])


lOMoARcPSD|49418476

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

WINTER – 2024 EXAMINATION


Model Answer – Only for the Use of RAC Assessors

Subject: Programming with Python Subject Code: 22616

def disp_price(self):
print("Price=$",self.price)
car1=Category()
car1.display()
car1.disp_price()
Output:
Name= Maruti
Price=$ 2000

Example 2: Inheritance using constructor.


class Vehicle: #parent class
def __init__(self,name):
self.name=name
def display(self):
print("Name= ",self.name)
class Category(Vehicle): #derived class
def __init__(self,name,price):
Vehicle.__init__(self,name)
# passing data to base class constructor
self.price=price
def disp_price(self):
print("Price=$ ",self.price)
car1=Category("Maruti",2000)
car1.display()
car1.disp_price()
car2=Category("BMW",5000)
car2.display()
car2.disp_price()
Output:
Name= Maruti
Price=$ 2000
Name= BMW
Price=$ 5000

Page 13 / 23

Downloaded by Fevicol ([email protected])


lOMoARcPSD|49418476

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

WINTER – 2024 EXAMINATION


Model Answer – Only for the Use of RAC Assessors

Subject: Programming with Python Subject Code: 22616

4. Attempt any THREE of the following: 12M


a) Explain loop control statement in python. 4M
Ans. Statements used to control loops and change the course of iteration
are called control statements. All the objects produced within the 2M for
local scope of the loop are deleted when execution is completed. listing of
statements
Python provides the following control statements.
1) Break statement 2M for
This command terminates the loop's execution and transfers the example
program's control to the statement next to the loop.

Example for letter in 'python programming':


if letter == 'y' or letter == 'm':
break

print('Current Letter :', letter)

output : Current Letter : y

2) Continue statement
This command skips the current iteration of the loop. The statements
following the continue statement are not executed once the Python
interpreter reaches the continue statement.
Example :
for letter in 'python program':
if letter == 'y' or letter == 'm':
continue
print('Current Letter :', letter)
Current Letter : p
Current Letter : t
Current Letter : h
Current Letter : o
Current Letter : n
Current Letter : p
Current Letter : r
Current Letter : o
Current Letter : g
Current Letter : r
Current Letter : a

Page 14 / 23

Downloaded by Fevicol ([email protected])


lOMoARcPSD|49418476

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

WINTER – 2024 EXAMINATION


Model Answer – Only for the Use of RAC Assessors

Subject: Programming with Python Subject Code: 22616

3) Pass statement
The pass statement is used when a statement is syntactically
necessary, but no code is to be executed.

Example : for letter in 'python':


pass
print('Last Letter :', letter)

Last Letter : n
b) Illustrate with example Method overloading 4M
Ans. It is the ability to define the method with the same name but with a
2M for
different number of arguments and data types. With this ability one explanation
method can perform different tasks, depending on the number of
arguments or the types of the arguments given. 2M for
example
Method overloading is a concept in which a method in a class
performs operations according to the parameters passed to it. As in
other languages we can write a program having two methods with
same name but with different number of arguments or order of
arguments but in python if we will try to do the same we will get the
following issue with method overloading in Python:
# to calculate area of rectangle
def area(length, breadth):
calc = length * breadth
print calc
#to calculate area of square
def area(size):
calc = size * size
print calc
area(3)
area(4,5)
Output:
9
TypeError: area() takes exactly 1 argument (2 given)

Page 15 / 23

Downloaded by Fevicol ([email protected])


lOMoARcPSD|49418476

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

WINTER – 2024 EXAMINATION


Model Answer – Only for the Use of RAC Assessors

Subject: Programming with Python Subject Code: 22616

Python does not support method overloading, that is, it is not possible
to define more than one method with the same name in a class in
Python.
This is because method arguments in python do not have a type. A
method accepting one argument can be called with an integer value, a
string or a double as shown in next
example.
class Demo:
def method(self, a):
print(a)
obj= Demo()
obj.method(50)
obj.method('Meenakshi')
obj.method(100.2)
Output:
50
Meenakshi
100.2
Same method works for three different data types. Thus, we cannot
define two methods with the same name and same number of
arguments but having different type as shown in the above example.
They will be treated as the same method. It is clear that method
overloading is not supported in python but that does not mean that we
cannot call a method with different number of arguments. There are a
couple of alternatives available in python that make it possible to call
the same method but with different number of arguments.erample
method overloading

c) Write a Python program to check for zero division errors 4M


exception. Each
Ans. a=int(input("Enter the value of a:")) correct
b=int(input("Enter the value of b:")) output 1M

Page 16 / 23

Downloaded by Fevicol ([email protected])


lOMoARcPSD|49418476

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

WINTER – 2024 EXAMINATION


Model Answer – Only for the Use of RAC Assessors

Subject: Programming with Python Subject Code: 22616

try:
ans=a/b
print("ANS :",ans)
except ZeroDivisionError:
print("Division by Zero........")

output :
Enter the value of a : 10
Enter the value of b : 0
Division by Zero..........
d) Write the output for the following if the variable fruit : .banana 4M
Ans. >> fruit [:3] Each
Output : ban correct
output 1M
>> fruit [3:]
Output : ana
>> fruit [3:3]
Output :
>> fruit [:]
Output : banana
e) Write a Python program to read contents from "a.txt" and write 4M
same contents in "b.txt". Any suitable
Ans. with open("a.txt", "r") as read_file, open("b.txt", "w") as write_file: program
with correct
content = read_file.read() syntax 4M
write_file.write(content)
5. Attempt any TWO of the following: 12M
a) Explain basic operation performed on set with suitable example. 6M
Ans. In Python, sets are a built-in data structure that allows you to perform 2M for each
a variety of operations. Python provides methods and operators to operation
perform the basic set operations, such as union, intersection,
difference, symmetric difference

1. Union ( | or union() )
The union of two sets combines all elements from both sets,
removing duplicates.
A = {1, 2, 3}
B = {3, 4, 5}
print( A | B) # Output: {1, 2, 3, 4, 5}
print( A.union(B)) # Output: {1, 2, 3, 4, 5}

Page 17 / 23

Downloaded by Fevicol ([email protected])


lOMoARcPSD|49418476

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

WINTER – 2024 EXAMINATION


Model Answer – Only for the Use of RAC Assessors

Subject: Programming with Python Subject Code: 22616

2. Intersection ( & or intersection() )


The intersection of two sets returns a new set with elements common
to both sets.
A = {1, 2, 3}
B = {3, 4, 5}
print(A & B) # Output: {3}
print(A.intersection(B))# Output: {3}

3. Difference ( - or difference() )
The difference of two sets returns a set containing elements present in
the first set but not in the second.
A = {1, 2, 3}
B = {3, 4, 5}
print( A– B) # Output: {1, 2}
print(A.difference(B))# Output: {1, 2}

b) How to write, import and alias modules. 6M


Ans. In Python, modules are files containing Python code, which can 2M for
include functions, classes, variables, and runnable code. You can each step
write, import, and alias modules to organize and reuse your code
efficiently.
1. Writing a Python Module
To write a Python module, you simply need to create a Python file
with a .py extension. For example, a file named my_module.py:
def greet(name):
return f"Hello, {name}!"
pi = 3.14159
class Calculator:
def add(self, a, b):
return a + b
def multiply(self, a, b):
return a * b
2. Importing a Module in Python
Once you have a module, you can import it into another Python file

Page 18 / 23

Downloaded by Fevicol ([email protected])


lOMoARcPSD|49418476

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

WINTER – 2024 EXAMINATION


Model Answer – Only for the Use of RAC Assessors

Subject: Programming with Python Subject Code: 22616

using the import statement.


importmy_module
print(my_module.greet("Alice")) # Output: Hello, Alice!
print(my_module.pi) # Output: 3.14159
calc = my_module.Calculator()
print(calc.add(2, 3)) # Output: 5
3. Aliasing a Module
You can create an alias for a module or a function using the as
keyword. This is often done to shorten long module names or make
code more readable.
# Importing a module with an alias
import my_module as mm
print(mm.greet("David")) # Output: Hello, David!
print(mm.pi) # Output: 3.14159
c) Design a class student with data members; Name, Roll No, 6M
Address. Create suitable method for reading and printing
students details. Defining
class 2M
Ans. class Student: Reading 2M
def __init__(self, name, roll_no, address): Printing 2M
self.name = name
self.roll_no = roll_no
self.address = address
defread_details(self):
self.name = input("Enter the student's name: ")
self.roll_no = input("Enter the student's roll number: ")
self.address = input("Enter the student's address: ")

defprint_details(self):
print("Student Details:")
print(f"Name: {self.name}")
print(f"Roll No: {self.roll_no}")
print(f"Address: {self.address}")

student = Student("", "", "")


student.read_details()

Page 19 / 23

Downloaded by Fevicol ([email protected])


lOMoARcPSD|49418476

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

WINTER – 2024 EXAMINATION


Model Answer – Only for the Use of RAC Assessors

Subject: Programming with Python Subject Code: 22616

student.print_details()

OUTPUT:
Enter the student's name:
Alice
Enter the student's roll number:101
Enterthestudent'saddress:123MainSt
Student Details:
Name:Alice
Roll No:101
Address:123MainSt
6. Attempt any TWO of the following: 12M
a) Determine various data types available in Python with example. 6M
Ans. Python provides a variety of built-in data types, which can be
classified into several categories based on their characteristics. Here's 2M for each
a detailed description of the most common data types in Python with category
examples:
1. Numeric Types
Numeric types are used to store numbers.
a. Integer (int)
An integer is a whole number without a decimal point.
x = 10 # Integer
y = -25 # Negative integer
print(x, type(x))
# Output: 10 <class 'int'>

b. Floating-Point (float)
A float is a number that has a decimal point or is in exponential form.
x = 3.14 # Float
y = -2.71 # Negative float
print(x, type(x))
# Output: 3.14 <class 'float'>

c. Complex Number (complex)


A complex number has a real part and an imaginary part, represented
as a + bj, where a and b are real numbers and j is the imaginary unit.
x = 2 + 3j# Complex number

Page 20 / 23

Downloaded by Fevicol ([email protected])


lOMoARcPSD|49418476

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

WINTER – 2024 EXAMINATION


Model Answer – Only for the Use of RAC Assessors

Subject: Programming with Python Subject Code: 22616

print(x, type(x)) # Output: (2+3j) <class 'complex'>

2. Sequence Types
Sequence types store an ordered collection of items.

a. String (str)
A string is a sequence of characters enclosed within single (') or
double (") quotes.
name = "John" # String
message = 'Hello, World!'
print(name, type(name)) # Output: John <class 'str'>
. List (list)
A list is an ordered, mutable collection that can contain elements of
any data type, including other lists.
fruits = ['apple', 'banana', 'cherry'] # List
print(fruits, type(fruits)) # Output: ['apple', 'banana', 'cherry'] <class
'list'>

3. Mapping Type
Mapping types store key-value pairs.
a. Dictionary (dict)
A dictionary is an unordered, mutable collection of key-value pairs,
where each key is unique.
person = {'name': 'Alice', 'age': 25, 'city': 'New York'}
print(person, type(person)) # Output: {'name': 'Alice', 'age': 25, 'city':
'New York'} <class 'dict'>

4. Set Types
Set types are used to store unordered collections of unique elements.
a. Set (set)
A set is an unordered collection of unique elements, and it is mutable
(you can add or remove items).
fruits = {'apple', 'banana', 'cherry'} # Set
print(fruits, type(fruits)) # Output: {'banana', 'apple', 'cherry'} <class
'set'>

Page 21 / 23

Downloaded by Fevicol ([email protected])


lOMoARcPSD|49418476

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

WINTER – 2024 EXAMINATION


Model Answer – Only for the Use of RAC Assessors

Subject: Programming with Python Subject Code: 22616

b) Write a Python program to read contents of first.txt file and 6M


write same content in second.txt file.
Ans. # Open the first.txt file in read mode with open('first.txt', 'r') as file1: Reading
# Read the content of the first file contents of
first file 3M
content = file1.read()
# Open the second.txt file in write mode (it will create the file if it
doesn't exist)
with open('second.txt', 'w') as file2: Writing
# Write the content to the second file contents of
first file to
file2.write(content) second file
print("Contents of first.txt have been copied to second.txt.") 3M

Explanation:
Opening first.txt:
The open() function is used with the 'r' mode to open first.txt in read
mode.
with open() is used to ensure the file is properly closed after the
operation is complete.
Reading the contents:
file1.read() reads the entire content of first.txt into the variable
content.
Opening second.txt:
The open() function is used with the 'w' mode to open second.txt in
write mode.
If second.txt does not exist, it will be created automatically.
Writing the contents:
file2.write(content) writes the content read from first.txt into
second.txt.
c) Explain Try-except-else-finally block used in exception handling 6M
in Python with example.
Ans. The try-except-else-finally block is a comprehensive way to handle Each
exceptions in Python. It allows you to test a block of code for errors explanatio
(try), handle the errors if they occur (except), execute code if no n ,syntax
errors occur (else), and execute cleanup code regardless of whether an and
error occurred or not (finally). example
2M
try:
# Code that might raise an exceptionexcept ExceptionType:
# Code to handle the exception
else:

Page 22 / 23

Downloaded by Fevicol ([email protected])


lOMoARcPSD|49418476

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

WINTER – 2024 EXAMINATION


Model Answer – Only for the Use of RAC Assessors

Subject: Programming with Python Subject Code: 22616

# Code that runs if no exception was raised


finally:
# Code that always runs (cleanup code)

Explanation of Components
try Block: Contains the code that might raise an exception.
except Block: Catches and handles the exception.
else Block: Executes if the try block succeeds without any exceptions.
finally Block: Executes regardless of whether an exception was raised
or not. Typically used for cleanup tasks.

Example:

try:
# Try to open and read a file
file = open("example.txt", "r")
content = file.read()
print(content)
except FileNotFoundError:
# Handle the specific exception if the file doesn't exist
print("Error: The file was not found.")
except IOError:
# Handle other I/O errors
print("Error: An IOError occurred.")
else:
# Executes if no exceptions were raised
print("File was read successfully!")
finally:
# Always executes, used to clean up resources
try:
file.close()
print("File has been closed.")
except NameError:
print("File object does not exist.")

Page 23 / 23

Downloaded by Fevicol ([email protected])

You might also like