0% found this document useful (0 votes)
19 views22 pages

XXXXX: e Some Difference in The Candidate's Answers and Model Answer. Candidate's Understanding

The document provides guidelines for examiners on assessing answers for the Winter 2022 examination in Programming with Python. It includes instructions on evaluating answers based on understanding rather than exact wording, as well as specific marking schemes for various questions. Additionally, it outlines the importance of considering answers written in both English and Marathi for first-year students.

Uploaded by

khodeyash54
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)
19 views22 pages

XXXXX: e Some Difference in The Candidate's Answers and Model Answer. Candidate's Understanding

The document provides guidelines for examiners on assessing answers for the Winter 2022 examination in Programming with Python. It includes instructions on evaluating answers based on understanding rather than exact wording, as well as specific marking schemes for various questions. Additionally, it outlines the importance of considering answers written in both English and Marathi for first-year students.

Uploaded by

khodeyash54
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/ 22

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION

(Autonomous) (Autonomous) (Autonomous)


(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________ __________________________________________________________________________________________________
WINTER – 2022 EXAMINATION != Not Equal to
Subject Name: Programming with Python Model Answer Subject Code: 22616 < Less than
> Greater than
Important Instructions to examiners: XXXXX <= Less than and Equal to
1) The answers should be examined by key words and not as word-to-word as given in the model answer scheme.
>= Greater than and Equal to
2) The model answer and the answer written by candidate may vary but the examiner may try to assess the
c) Describe Tuples in Python. 2M
understanding level of the candidate.
3) The language errors such as grammatical, spelling errors should not be given more Importance (Not applicable for Ans A tuple is a collection of items which is ordered and unchangeable. 2M for
subject English and Communication Skills. Tuples are the sequence or series values of different types separated by commas (,). Definition.
4) While assessing figures, examiner may give credit for principal components indicated in the figure. The figures Example: tup1=(10,20,30)
drawn by candidate and model answer may vary. The examiner may give credit for any equivalent figure drawn. 2. Attempt any THREE of the following: 12 M
5) Credits may be given step wise for numerical problems. In some cases, the assumed constant values may vary and d) Write use of lambda function in python. 2M
there may be some difference in the candidate’s answers and model answer. a) Describe bitwise operators in Python with example. 4M
6) In case of some questions credit may be given by judgement on part of examiner of relevant answer based on Ans The lambda function, which is also called anonymous function. A lambda function can 2M for use Ans Bitwise operators acts on bits and performs bit by bit operation. Assume a=10 (1010) 4M (for any
candidate’s understanding. take any number of arguments, but can only have one expression. and b=4 (0100) four, 1M each)
7) For programming language papers, credit may be given to any other program based on equivalent concept. Syntax: lambda arguments : expression Operator Meaning Description Example
8) As per the policy decision of Maharashtra State Government, teaching in English/Marathi and Bilingual (English + Example: x= lambda a,b : a*b & Binary AND This operation a &b =
Marathi) medium is introduced at first year of AICTE diploma Programme from academic year 2021-2022. Hence if Print(x(10,5)
the students in first year (first and second semesters) write answers in Marathi or bilingual language (English
performs AND 1010 &
Output: 50 operation 0100 =
+Marathi), the Examiner shall consider the same and assess the answer based on matching of concepts with
model answer. between 0000 =0
e) Write syntax of defining class in Python. 2M
operands.
Q. Sub Answer Marking Operator copies a
Ans class <ClassName>: 2M for syntax bit, to the result,
No. Q. Scheme <statement1>
N. if it exists in both
<statement2> operands
.
1 Attempt any FIVE of the following: 10 M | Binary OR This operation a|b = 1010 |
.
performs OR 0100 =
a) List Python features. (Any four) 2M <statementN>
operation 1110 = 14
between
f) List file operations in Python. 2M
Ans  Easy to Learn and Use 2M (1/2 M each) operands. It
 Interactive Mode Any Four copies a bit, if it
 Expressive Language
Ans  Opening file (using open() function) 2M exists in either
 Interpreted Language  Reading file (using read() function) operand.
 Cross-platform Language  Writing file (using write() function) ^ Binary XOR This operation a^b=1010 ^
 Portable  Copy files performs XOR 0100 =
 Free and Open Source  Delete files (using remove() function) operations 1110 =14
 Closing file (Using close() function) between
 Object-Oriented Language
g) Describe indentation in Python. 2M operands. It
 Extensible
copies the bit, if it
 Large Standard Library Ans Indentation refers to the spaces at the beginning of a code line. Python indentation 2M is set in one
 GUI Programming Support refers to adding white space before a statement to a particular block of code. In another operand but not
 Integrated word, all the statements with the same space to the right, belong to the same code both.
 Databases block. ~ Binary Ones It is unary ~a= ~ 1010
 Scalable
Complement operator and has = 0101
b) List comparision operators in Python. 2M the effect of
Ans Comparison operators in Python are 2M (1M each) 'flipping' bits i.e.
opposite the bits
Operator Meaning of operand.
== Equal to << Binary Left The left operand's a<<2 =
Page No: 1 | 21 Page No: 2 | 21 Page No: 3 | 21

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________ __________________________________________________________________________________________________
Shift value is moved 1010 << 2
left by the =101000 = test()
number of bits 40 print("global variable=",g)
specified by the
right operand. output:
>> Binary Right The left operand's a>>2 = local variable= 20
Shift value is moved 1010 >> 2 Global variable= 10
right by the =0010 = 2 global variable= 10
number of bits
specified by the
right operand. d) Write python program to illustrate if else ladder. 4M
b) Write any four methods of dictionary. 4M
Ans i = 20 4M (for correct
Ans 4M (any four, if (i == 10): program and
1M each) print ("i is 10") logic)
elif (i == 15):
print ("i is 15")
elif (i == 20):
print ("i is 20")
else:
print ("i is not present")

output:
i is 20
c) What is local and global variables? Explain with appropriate example. 4M (Similar type of program can consider)

Ans  Global variables: global variables can be accessed throughout the program 4M (2M for
3. Attempt any THREE of the following: 12 M
body by all functions. explanation
 Local variables: local variables can be accessed only inside the function in and 2M for a) Write basis operations of list. 4M
which they are declared example)
Concept Diagram: Ans 1)Accessing values in list: Any two
Accessing elements liters from a list in Python is a method to get values that are stared operations:
in the list at a particular location or index.
To access values in lists, use the square brackets for slicing along with the index or 2 M for each
indices to obtain value available at that index.
Example: accessing list values.
>>> list1 = ["one","two",3,10,"six",20]
>>> list1[0]
'one'
>>> list1[-2]
A global variable (x) can be reached and modified anywhere in the code, local 'six'
variable (z) exists only in block 3. >>> list1[1:3]
Example: ['two', 3]
g=10 #global variable g >>> list1[3:]
def test(): [10, 'six', 20]
l=20 #local variable l >>> list1[:4]
print("local variable=",l) ['one', 'two', 3, 10]
# accessing global variable >>>
print("Global variable=",g)

Page No: 4 | 21 Page No: 5 | 21 Page No: 6 | 21


MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________ __________________________________________________________________________________________________
2) Deleting Values in List • Multiple values can be added into list. We can use assignment operator (=) to change
an item or a
The pop() method in Python is used to remove a particular item/element from the given range of items. b) Write Python code for finding greatest among four numbers. 4M
index in the list. The pop() method removes and returns the last item if index is not
• We can update items of the list by simply assigning the value at the particular index
provided. This helps us implement lists as stacks (first in, last out data structure). Ans list1 = [ ] Any correct
position. We
>>> list= [10, 20, 30, 40] num = int(input("Enter number of elements in list: ")) logic program
can also remove the items from the list using remove() or pop() or del statement.
>>> list for i in range(1, num + 1): 4M
[10, 20, 30, 40] element = int(input("Enter elements: "))
>>> list1= [10, 20, 30, 40, 50]
30 list1.append(element)
>>> list1
>>> list print("Largest element is:", max(list1))
[10, 20, 30, 40, 50]
[10, 20, 40] Output:
>>> list1[0]=0 # change 0th index element
>>> list.pop() Enter number of elements in list: 4
>>> list1
40 Enter elements: 10
[0, 20, 30, 40, 50]
>>> list Enter elements: 20
>>> list1[-1]=60 # change last index element
[10, 30] Enter elements: 45
>>> list1
We can delete one or more items from a list using the keyword del. It can even delete Enter elements: 20
[0, 20, 30, 40, 60]
the list entirely. But it does not store the value for further use Largest element is: 45
>>> list1[1]=[5,10] # change 1st index element as sublist
>>> list= [10, 20, 30, 40] c) Illustrate with example method over loading. 4M
>>> list1
>>> list
[10, 20, 30, 40]
[0, [5, 10], 30, 40, 60] Ans • Method overloading is the ability to define the method with the same name but with a Explanation
>>> list1[1:1]=[3,4] # add elements to a list at the desired location different number of arguments and data types. 1 M and
>>> del (list[1]) # del() with index
>>> list
>>> list1 • With this ability one method can perform different tasks, depending on the number of Example 3 M
[0, 3, 4, [5, 10], 30, 40, 60] arguments or the types of the arguments given.
[10, 30, 40]
• Method overloading is a concept in which a method in a class performs operations
>>> del list[2] # del with index
4 Indexing according to the parameters passed to it.
>>> list
There are various ways in which we can access the elements of a list. Example: With a method to perform different operations using method overloading.
[10, 30]
List Index: We can use the index operator [] to access an item in a list. Index starts class operation:
The remove() method in Python issued to remove a particular element from the list. We
from 0. So, a list having 5 elements will have index from 0 to 4. def add(self,a,b):
use the remove() method if we know the item that we want to remove or delete from the
Example: return a+b
list (but not the index).
>>> list1=[10,20,30,40,50] op1=operation()
>>> list=[10,"one",20,"two"]
>>> list1[0] # To add two integer numbers
>>> list.remove(20)
10 print("Addition of integer numbers=",op1.add(10,20))
>>> list >>> list1[4]
[10, 'one', 'two'] # To add two floting point numbers
50
>>> list.remove("one") print("Addition of integer numbers=",op1.add(11.12,12.13))
>>> list1[1:3]
>>> list [20, 30] # To add two strings
[10, 'two'] print("Addition of integer numbers=",op1.add("Hello","Python"))
>>> 5. List Slicing Output:
The slicing operator returns a subset of a list called slice by specifying two indices, i.e. Addition of integer numbers= 30
3. Updating Lists: start and end. Addition of integer numbers= 23.25
• List are mutable, meaning their elements can be changed or updated unlike string or Syntax: Addition of integer numbers= HelloPython
tuple. List_variable[start_index:end_index] Python does not support method overloading, that is, it is not possible to define more
• Mutability is the ability for certain types of data to be changed without entirely Example: than one method with the same name in a class in Python.
recreating it. Using >>> l1=([10,20,30,40,50]) • This is because method arguments in python do not have a type. A method accepting
mutable data types can allow programs to operate quickly and efficiently. >>> l1[1:4] one argument can be called with an integer value, a string or a double as shown in next
[20, 30, 40] example.
Page No: 7 | 21 Page No: 8 | 21 Page No: 9 | 21

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________ __________________________________________________________________________________________________
class Demo: except Exception1: Ans Python Command line arguments are input parameters passed to the script when 1 M for
def method(self, a): If there is Exception1, then execute this block. executing them. Almost all programming language provide support for command line definition and
print(a) except Exception2: arguments. Then we also have command line options to set some specific options for 3 M for
the program. program
obj= Demo() If there is Exception2, then execute this block.
obj.method(50) ...................... There are many options to read python command line arguments. The three most
obj.method('Meenakshi') else: common ones are:
obj.method(100.2) If there is no exception then execute this block. Python sys.argv
Output: Python getopt module
50 Example: For try-except clause/statement. Python argparse module
Meenakshi n=10
100.2 m=0 Program:
d) Explain how try-catch block is used for exception handling in python. 4M try: import sys
n/m x=int(sys.argv[1])
Ans • In Python, exceptions can be handled using a try statement. A try block Proper
except ZeroDivisionError: y=int(sys.argv[2])
consisting of one or more statements is used by programmers to partition code explanation
print("Divide by zero error") sum=x+y
that might be affected by an exception.
• A critical operation which can raise exception is placed inside the try clause and the 4 M else: print("The addition is :",sum)
code that handles exception is written in except clause. print (n/m)
• The associated except blocks are used to handle any resulting exceptions thrown in Output:
Output:
the try block. That is we want the try block to succeed and if it does not succeed, we Divide by zero error
want to control to pass to the catch block. C:\Python34\python sum.py 6 4
• If any statement within the try block throws an exception, control immediately shifts The addition is : 10
to the catch block. If no exception is thrown in the try block, the catch block is skipped. 4. Attempt any THREE of the following: 12 M c) Write python code to count frequency of each characters in a given file. 4M
• There can be one or more except blocks. Multiple except blocks with different
a) Compare list and dictionary. (Any 4 points) 4M Ans import collections Any proper
exception names can be chained together.
import pprint logic program
• The except blocks are evaluated from top to bottom in the code, but only one except Ans List Dictionary Any four point, 4M
block is executed for each exception that is thrown. file_input = input('File Name: ')
• The first except block that specifies the exact exception name of the thrown exception List is a collection of index values pairs Dictionary is a hashed structure of 1 M for 1 point with open(file_input, 'r') as info:
is executed. If no except block specifies a matching exception name then an except as that of array in c++. key and value pairs. count = collections.Counter(info.read().upper())
block that does not have an exception name is selected, if one is present in the code. value = pprint.pformat(count)
List is created by placing elements in [ ] Dictionary is created by placing
• For handling exception in Python, the exception handler block needs to be written print(value)
separated by commas “, “ elements in { } as “key”:”value”,
which consists of set of statements that need to be executed according to raised d) Write python program to read contents of abc.txt and write same content to 4M
each key value pair is separated by
exception. There are three blocks that are used in the exception handling process, pqr.txt.
commas “, “
namely, try, except and finally.
1. try Block: A set of statements that may cause error during runtime are to be written The indices of list are integers starting The keys of dictionary can be of any Ans with open('abs.txt','r') as firstfile, open('prq.txt','w') as secondfile: Any proper
in the try from 0. data type. # read content from first file logic program
block. for line in firstfile: for 4 M
2. except Block: It is written to display the execution details to the user when certain The elements are accessed via indices. The elements are accessed via key- # write content to second file
exception occurs in the program. The except block executed only when a certain type as values. secondfile.write(line)
exception occurs in the execution of statements written in the try block. The order of the elements entered are There is no guarantee for
maintained. maintaining order.
5. Attempt any TWO of the following: 12 M
Syntax:
try: b) What is command line argument? Write python code to add b) two 4M
a) Write different data types in python with suitable example. 6M
D the operations here numbers given as input from command line arguments and print its sum.
...................... Ans Data types in Python programming includes:
 Numbers: Represents numeric data to perform mathematical operations.
Page No: 10 | 21 Page No: 11 | 21 Page No: 12 | 21
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________ __________________________________________________________________________________________________
 String: Represents text characters, special symbols or alphanumeric data. 5. String Data Type: String is a collection of group of characters. Strings are identified 8. Dictionary: Dictionary is an unordered collection of key-value pairs. It is the same as
 List: Represents sequential data that the programmer wishes to sort, merge etc. as a contiguous set of characters enclosed in single quotes (' ') or double quotes (" "). the hash table type. The order of elements in a dictionary is undefined, but we can
6m for data
 Tuple: Represents sequential data with a little difference from list. types
Any letter, a number or a symbol could be a part of the string. Strings are iterate over the following:
 Dictionary: Represents a collection of data that associate a unique key with each unchangeable (immutable). Once a string is created, it cannot be modified. o The key
value. Example: For string data type. o The value
 Boolean: Represents truth-values (true or false). >>> s1="Hello" #string in double quotes o The items (key-value pairs) in a dictionary.
>>> s2='Hi' #string in single quotes When we have the large amount of data, the dictionary data type is used. Items in
1. Integers (int Data Type): An integer is a whole number that can be positive (+) or >>> s3="Don't open the door" #single quote string in double quotes dictionaries are enclosed in curly braces { } and separated by the comma (,). A colon (:)
negative (−). Integers can be of any length, it is only limited by the memory available. >>> s4='I said "yipee"' #double quote string in single quotes is used to separate key from value. Values can be assigned and accessed using square
Example: For number data types are integers. >>>type(s1) braces ([]).
>>>a=10 <class 'str'> Example: For dictionary data type.
>>>b -10 >>> dic1={1:"First","Second":2}
To determine the type of a variable type() function is used. 6. List Data Type: List is an ordered sequence of items. It is one of the most used >>> dic1
>>>type(a) datatype in Python and is very flexible. {1: 'First', 'Second': 2}
>>> <class 'int'> List can contain heterogeneous values such as integers, floats, strings, tuples, lists and >>> type(dic1)
dictionaries but they are commonly used to store collections of homogeneous objects. <class 'dict'>
2. Boolean (Bool Data Type: The simplest build-in type in Python is the bool type, it The list datatype in Python programming is just like an array that can store a group of >>> dic1[3]="Third"
represents the truth-values False and True. Internally the true value is represented as elements and we can refer to these elements using a single name. Declaring a list is >>> dic1
1 and false is 0. pretty straight forward. Items separated by commas ( , ) are enclosed within brackets [ {1: 'First', 'Second': 2, 3: 'Third'}
For example ]. >>> dic1.keys()
>>>a = 18 > 5 Example: For list. dict_keys([1, 'Second', 3])
>>>print(a) >>> first=[10, 20, 30] # homogenous values in list >>> dic1.values()
True >>> second=["One","Two","Three"] # homogenous values in list dict_values(['First', 2, 'Third'])
b=2>3 >>> first >>>
print(b) [10, 20, 30]
>>> second b) Example module. How to define module. 6M
False
['One', 'Two', 'Three'] Ans A module allows you to logically organize your Python code. Grouping related code 2 M for
3. Floating-Point/Float Numbers (Float Data Type): Floating-point number or Float is >>> first + second # prints the concatenated lists into a module makes the code easier to understand and use. A module is a Python module
a positive or negative number with a fractional part. A floating point number is [10, 20, 30, 'One', 'Two', 'Three'] object with arbitrarily named attributes that you can bind and reference. explanation
accurate up to 15 decimal places. Integer and floating points are separated by decimal
points. 1 is integer, 1.0 is floating point number. 7. Tuple Data Type: Tuple is an ordered sequence of items same as list. The only Simply, a module is a file consisting of Python code. A module can define functions,
difference is that tuples are immutable. classes and variables. A module can also include runnable code.
Example: Floating point number.
x=10.1 Tuples once created cannot be modified. It is defined within parentheses ( ) where Example
type(x) items are separated by commas ( , ).
<class 'float'> A tuple data type in python programming is similar to a list data type, which also The Python code for a module named aname normally resides in a file named
contains heterogeneous items/elements. aname.py. Here's an example of a simple module, support.py 2 M for
Example: For tuple. creating
4. Complex Numbers (Complex Data Type): Complex numbers are written in the form, def print_func( par ): module
x + yj, where x is the real part and y is the imaginary part. >>> a=(10,'abc',1+3j)
print "Hello : ", par
Example: >>> a
return
Complex number. (10, 'abc', (1+3j))
To create a module just save the code you want in a file with the file extension .py:
>>>x = 3+4j >>> a[0] Example
>>>print(x.real) 10 Save this code in a file named mymodule.py
3.0 >>> a[0]=20 def greeting(name):
>>>print(x.imag) Traceback (most recent call last): print("Hello, " + name)
4.0 File "<pyshell#12>", line 1, in <module>
Now we can use the module we just created, by using the import statement: 2 M for
accessing/using
Page No: 13 | 21 Page No: 14 | 21 Page No: 15 | 21

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________ __________________________________________________________________________________________________
Example module Example:
*If students have attempted by using “Tuple” then
Import the module named mymodule, and call the greeting function: # int
num1 = 10
import mymodule
#To create tuple num2 = 100
mymodule.greeting("ABC")
c) Write python program to perform following operations on Set (Instead of 6M tuple1=(10,20,30,40,50)
print (tuple1) # float
Tuple)
#Access tuple values a = 10.5
i) Create set print (tuple1[1]) b = 8.9
ii) Access set Element print (tuple1[0:3])
# complex numbers
iii) Update set # deleting tuple
x = 3 + 4j
iv) Delete set del tuple1
y = 9 + 8j
print (tuple1)
Ans # To Create set
2. String
S={10,20,30,40,50} output:
6m for any
suitable (10, 20, 30, 40, 50) A string is usually a bit of text (sequence of characters). In Python we use ” (double
# To Access Elements from set
program 20 quotes) or ‘ (single quotes) to represent a string.
print (S) (10, 20, 30)
There are several ways to create strings in Python:
Traceback (most recent call last):
#To add element into set using add method
S.add(60) (If students
File "C:\Users\Vijay Patil\AppData\Local\Programs\Python\Python310\temp.py", line 1. We can use ‘ (single quotes), see the string str in the following code.
9, in <module>
print(S) attempted with 2. We can use ” (double quotes), see the string str2 in the source code below.
“set” give print (tuple1)
#To update set using update method marks as per NameError: name 'tuple1' is not defined. Did you mean: 'tuple'? 3. Triple double quotes “”” and triple single quotes ”’ are used for creating multi-line
S.update(['A','B']) marking strings in Python.
print(S) scheme)
Example:
#To Delete element from Set using discard() method OR
str = 'beginnersbook'
S.discard(30) (If students str2 = "Chaitanya"
print(S) 6. Attempt any TWO of the following: 12 M
attempted with # multi-line string
“Tuple” a) Explain mutable and immutable data structures. 6M str3 = """Welcome to
#To delete element from set using remove() method Pythonsbook"""
S.remove('A') Then Ans The data types in Python are divided in two categories: 3m for mutable
print(S) Immutable data types – Values cannot be changed. Immutable data types in Python are data structure str4 = '''This is a tech
2M-create
1. Numbers and 3m for paper'''
#To delete element from set using pop() method Tuple
2. String immutable data
S.pop() 2M-Access 3. Tuple structure
print(S) tuple Mutable data types – Values can be changed. Mutable data types in Python are: 3. Tuple
1. List
2M-delete In Python, a tuple is similar to List except that the objects in tuple are immutable which
output: 2. Dictionaries
Tuple) means we cannot change the elements of a tuple once assigned. On the other hand, we
{50, 20, 40, 10, 30} 3. Sets
can change the elements of a list.
{50, 20, 40, 10, 60, 30}
{'B', 50, 20, 'A', 40, 10, 60, 30} 1. Numbers To create a tuple in Python, place all the elements in a () parenthesis, separated by
{'B', 50, 20, 'A', 40, 10, 60} Python supports integers, floats and complex numbers. commas. A tuple can have heterogeneous data items, a tuple can have string and list as
{'B', 50, 20, 40, 10, 60} An integer is a number without decimal point for example 5, 6, 10 etc. data items as well.
{50, 20, 40, 10, 60} A float is a number with decimal point for example 6.7, 6.0, 10.99 etc. Example
A complex number has a real and imaginary part for example 7+8j, 8+11j etc. # tuple of strings
(Any other suitable example can consider) my_data = ("hi", "hello", "bye")
Page No: 16 | 21 Page No: 17 | 21 Page No: 18 | 21
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________ __________________________________________________________________________________________________
Create suitable method for reading and printing students details.
# tuple of int, float, string # function feed
my_data2 = (1, 2.8, "Hello World") Ans class Student: 2 M for class def feed(self):
definition print("I eat only plants. I am vegetarian.")
def getStudentDetails(self):
# tuple of string and list
my_data3 = ("Book", [1, 2, 3]) self.rollno=input("Enter Roll Number : ") herbi = Herbivorous()

# tuples inside another tuple self.name = input("Enter Name : ") herbi.feed()


# nested tuple # calling some other function
self.address =input("Enter Address : ")
my_data4 = ((2, 3, 4), (1, 2, "hi")) herbi.breathe()
def printStudentDetails(self):
4. List 2 M to define Output:
A list is a data type that allows you to store various types data in it. List is a compound print(self.rollno,self.name, self.address) functions I eat only plants. I am vegetarian.
data type which means you can have different-2 data types under a list, for example we I breathe oxygen.
can have integer, float and string items in a same list. S1=Student()
To create a list all you have to do is to place the items inside a square bracket [] S1.getStudentDetails()
separated by comma ,.`
Example: print("Student Details ")
# list of floats
num_list = [11.22, 9.9, 78.34, 12.0] S1.printStudentDetails ()

# list of int, float and strings Output: 2 M to create


mix_list = [1.13, 2, 5, "beginnersbook", 100, "hi"] objects
Enter Roll Number : 001
Enter Name : ABC
# an empty list
nodata_list = [] Enter Address : New York
Student Details :
5. Dictionaries 001 ABC New York
Dictionary is a mutable data type in Python. A python dictionary is a collection of key (Any suitable program can consider)
and value pairs separated by a colon (:), enclosed in curly braces {}. c) Create a parent class named Animals and a child class Herbivorous which will 6M
extend the class Animal. In the child class Herbivorous over side the method feed (
Left side of the colon(:) is the key and right side of the : is the value. ). Create a object
mydict = {'StuName': 'Ajeet', 'StuAge': 30, 'StuCity': 'Agra'} Ans # parent class 2 M to create
class Animal: parent class
6. Sets # properties
multicellular = True
Set is an unordered and unindexed collection of items in Python. Unordered means # Eukaryotic means Cells with Nucleus
when we display the elements of a set, it will come out in a random order. Unindexed eukaryotic = True
means, we cannot access the elements of a set using the indexes like we can do in list
and tuples. # function breath 2 M to define
def breathe(self): child class
The elements of a set are defined inside curly brackets and are separated by commas. print("I breathe oxygen.")
For example –
myset = {1, 2, 3, 4, "hello"} # function feed
def feed(self):
print("I eat food.")
2 M to create
b) Design a class student with data members; Name, roll number address. 6M # child class object and call
class Herbivorous(Animal): function
Page No: 19 | 21 Page No: 20 | 21 Page No: 21 | 21

SUMMER-2022 EXAMINATION The List has the variable The tuple has the fixed length f) How to give single and multiline comment in Python 2M (1m each)
Subject Name: Programming with Python Model Answer Subject Code: 22616 length Single line comment: Single-line comments are created simply by
List operations are more error Tuples operations are safe beginning a line with the hash (#) character, and they are
Important Instructions to examiners: prone. automatically terminated by the end of line.
1. The answers should be examined by key words and not as word-to-word as given in Lists can be used to store Tuples are used to store only Example:
homogeneous and heterogeneous elements. # print is a statement
the model answer scheme.
heterogeneous elements. print(‘Hello Python’)
2. The model answer and the answer written by candidate may vary but the examiner
List is useful for insertion and Tuple is useful for readonly
may try to assess the understanding level of the candidate. Multi line comment: Python multi-line comment is a piece of text
deletion operations. operations like accessing
3. The language errors such as grammatical, spelling errors should not be given more elements. enclosed in a delimiter (""") Triple quotation marks.
Importance (Not applicable for subject English and Communication Skills. List iteration is slower and is Tuple iteration is faster. Example:
4. While assessing figures, examiner may give credit for principal components time consuming. """ Multi-line comment used
indicated in the figure. The figures drawn by candidate and model answer may vary. d) Explain Local and Global variable 2M (1m each) print("Python Comments") """
The examiner may give credit for any equivalent figure drawn. Local Variables: Local variables are those which are initialized or
5. Credits may be given step wise for numerical problems. In some cases, the assumed inside a function and belongs only to that particular function. It To add a multiline comment you could insert a # for each line:
constant values may vary and there may be some difference in the candidate’s cannot be accessed anywhere outside the function Example:
answers and model answer. Example: #This is a comment
def f(): #written in
6. In case of some questions credit may be given by judgement on part of examiner of
# local variable #more than just one line
relevant answer based on candidate’s understanding. s = "I love Python Programming" print("Hello, World!")
7. For programming language papers, credit may be given to any other program based print(s)
g) List different modes of opening file in Python 2M
on equivalent concept. # Driver code
f() Modes for opening file: (Any 2 names 2M)
8. As per the policy decision of Maharashtra State Government, teaching in • r: open an existing file for a read operation.
Output
English/Marathi and Bilingual (English + Marathi) medium is introduced at first year I love Python Programming • w: open an existing file for a write operation. If the file
of AICTE diploma Programme from academic year 2021-2022. Hence if the students already contains some data then it will be overridden.
in first year (first and second semesters) write answers in Marathi or bilingual Global Variables: The global variables are those which are defined
outside any function and which are accessible throughout the • a: open an existing file for append operation. It won’t
language (English +Marathi), the Examiner shall consider the same and assess the
program i.e. inside and outside of every function. override existing data.
answer based on matching of concepts with model answer.
Example: • r+: To read and write data into the file. The previous
# This function uses global variable s data in the file will be overridden.
Q. Sub Answer Marking Scheme
No. Q. N.
def f(): • w+: To write and read data. It will override existing data.
1 Attempt Any FIVE of the following 10
print("Inside Function", s) • a+: To append and read data from the file. It won’t
a) Name different modes of Python 2M (1m each) override existing data.
# Global scope
Python has two basic modes:
s = "I love Python Programming"
• Script (Normal Mode) 2 Attempt any THREE of the following 12
f()
• Interactive Mode print("Outside Function", s)
a) Write a program to print following 4M (for correct
b) List identity operators in python 2M (1m each) 1 program and
Identity operators in Python are 12 logic)
Output:
• is 123
Inside Function I love Python Programming
• is not 1234
Outside Function I love Python Programming
c) Give two differences between list and tuple 2M (1m for each e) Define class and object in python 2M (Any suitable
difference, any 2 for i in range(1,5):
List Tuple Class: A class is a user-defined blueprint or prototype from which definition: 1M
difference) for j in range(1,i+1):
Lists are mutable Tuples are immutable objects are created. Classes provide a means of bundling data Each)
print(j,end=' ')
Lists consume more memory Tuple consume less memory and functionality together.
print()
as compared to the list
b) Explain four Buit-in tuple functions in python with example 4M ( 1M for each
Lists have several built-in Tuple does not have many Object: An object is an instance of a class that has some
function with
methods built-in methods. attributes and behavior. Objects can be used to access the
example)
The unexpected changes and In tuple, it is hard to take attributes of the class.
errors are more likely to occur place.

Page 1 of 23 Page 2 of 23 Page 3 of 23


statements Example: For number data types are integers.
. >>>a=10
. >>>b -10
Example: To determine the type of a variable type() function is used.
def square( x ):
>>>type(a)
print("Square=",x*x)
>>> <class 'int'>
# Driver code
square(2) 2. Boolean (Bool Data Type: The simplest build-in type in
Output: Python is the bool type, it represents the truth values False
Square= 4 and True. Internally the true value is represented as 1 and
d) Write a program to create class EMPLOYEE with ID and NAME 4M (for correct false is 0.
and display its contents. program and For example
class employee : logic) >>>a = 18 > 5
id=0 >>>print(a)
name="" True
def getdata(self,id,name): b=2>3
self.id=id
print(b)
self.name=name
def showdata(self):
False
print("ID :", self.id)
print("Name :", self.name) 3. Floating-Point/Float Numbers (Float Data Type): Floating-
point number or Float is a positive or negative number with
e = employee() a fractional part. A floating point number is accurate up to 15
e.getdata(11,"Vijay") decimal places. Integer and floating points are separated by
e.showdata() decimal points. 1 is integer, 1.0 is floating point number.
c) Explain how to use user defined function in python with example 4M (2m for Example: Floating point number.
• In Python, def keyword is used to declare user defined explanation and Output: x=10.1
functions. 2m for example) ID : 11 type(x)
Name : Vijay
• The function name with parentheses (), which may or may <class 'float'>
not include parameters and arguments and a colon: 3 Attempt any THREE of the following 12
• An indented block of statements follows the function a) List data types used in Python. Explain any two with 4M (2m for list, 4. Complex Numbers (Complex Data Type): Complex
name and arguments which contains the body of the example and 2m for two numbers are written in the form, x + yj, where x is the real
function. Data types in Python programming includes: example) part and y is the imaginary part.
Syntax: • Numbers: Represents numeric data to perform Example:
def function_name(): mathematical operations. Complex number.
statements • String: Represents text characters, special symbols or
. >>>x = 3+4j
alphanumeric data. >>>print(x.real)
.
• List: Represents sequential data that the programmer 3.0
Example:
def fun(): wishes to sort, merge etc. >>>print(x.imag)
print(“User defined function”) • Tuple: Represents sequential data with a little 4.0
fun() difference from list.
output: • Dictionary: Represents a collection of data that 5. String Data Type: String is a collection of group of
User defined function associate a unique key with each value. characters. Strings are identified as a contiguous set of
• Boolean: Represents truth values (true or false). characters enclosed in single quotes (' ') or double quotes ("
Parameterized function: The function may take arguments(s) also
"). Any letter, a number or a symbol could be a part of the
called parameters as input within the opening and closing 1. Integers (int Data Type): An integer is a whole number string. Strings are unchangeable (immutable). Once a string
parentheses, just after the function name followed by a colon.
that can be positive (+) or negative (−). Integers can be of any is created, it cannot be modified.
Syntax:
def function_name(argument1, argument2, ...):
length, it is only limited by the memory available. Example: For string data type.

Page 4 of 23 Page 5 of 23 Page 6 of 23

>>> s1="Hello" #string in double quotes 8. Dictionary: Dictionary is an unordered collection of key- it item is in list or in >>> print("Hello"
>>> s2='Hi' #string in single quotes value pairs. It is the same as the hash table type. The order sequence. not in x)
>>> s3="Don't open the door" #single quote string in double of elements in a dictionary is undefined, but we can iterate False
quotes over the following:
>>> s4='I said "yipee"' #double quote string in single quotes o The key Assignment Operators (Augmented Assignment Operators):
Assignment operators are used in Python programming to assign
>>>type(s1) o The value
values to variables. The assignment operator is used to store the
<class 'str'> o The items (key-value pairs) in a dictionary.
value on the right-hand side of the expression on the left-hand side
When we have the large amount of data, the dictionary data variable in the expression.
6. List Data Type: List is an ordered sequence of items. It is type is used. Items in dictionaries are enclosed in curly braces For example, a = 5 is a simple assignment operator that assigns the
one of the most used datatype in Python and is very flexible. { } and separated by the comma (,). A colon (:) is used to value 5 on the right to the variable a on the left.
List can contain heterogeneous values such as integers, separate key from value. Values can be assigned and There are various compound operators in Python like a += 5 that
floats, strings, tuples, lists and dictionaries but they are accessed using square braces ([]). adds to the variable and later assigns the same. It is equivalent to
commonly used to store collections of homogeneous Example: For dictionary data type. a = a + 5.
objects. The list datatype in Python programming is just like >>> dic1={1:"First","Second":2} Following table shows assignment operators in Python
an array that can store a group of elements and we can refer >>> dic1 programming:
to these elements using a single name. Declaring a list is {1: 'First', 'Second': 2} Sr. Operator Description Example
pretty straight forward. Items separated by commas ( , ) are >>> type(dic1) No.
enclosed within brackets [ ]. <class 'dict'> 1 = Assigns values from right c=a+b
Example: For list. >>> dic1[3]="Third" side operands to assigns value
>>> first=[10, 20, 30] # homogenous values in list >>> dic1 of a + b
left side operand.
>>> second=["One","Two","Three"] # homogenous values in {1: 'First', 'Second': 2, 3: 'Third'}
into c
list >>> dic1.keys()
>>> first dict_keys([1, 'Second', 3]) 2 += It adds right operand to c += a is
[10, 20, 30] >>> dic1.values() the left operand and equivalent to
>>> second dict_values(['First', 2, 'Third']) assign the result to left c=c+a
['One', 'Two', 'Three'] >>> operand.
>>> first + second # prints the concatenated lists b) Explain membership and assignment operators with 4M: 2m for
[10, 20, 30, 'One', 'Two', 'Three'] example membership 3 −= It subtracts right operand c −= a is
Membership Operators: The membership operators in Python are operators and from the left equivalent to
7. Tuple Data Type: Tuple is an ordered sequence of items used to find the existence of a particular element in the sequence, 2m for operand and assign the c=c−a
same as list. The only difference is that tuples are immutable. and used only with sequences like string, tuple, list, dictionary etc. assignment result to left operand.
Tuples once created cannot be modified. It is defined within Membership operators are used to check an item or an element operators
that is part of a string, a list or a tuple. A membership operator 4 *= It multiplies right operand operand and
parentheses ( ) where items are separated by commas ( , ).
reduces the effort of searching an element in the list. Python with the left assign the
A tuple data type in python programming is similar to a list
provides ‘in’ and ‘not in’ operators which are called membership result to left
data type, which also contains heterogeneous operand and assign the operand.
operators and used to test whether a value or variable is in a
items/elements. result to left operand.
sequence.
Example: For tuple. c *= a is
Sr. Operator Description Example equivalent to
>>> a=(10,'abc',1+3j) No
>>> a c=c*a
(10, 'abc', (1+3j)) 1 in True if value is >>> x="Hello
found in list or in World" 5 /= It divides left operand c /= a is
>>> a[0]
sequence, and false >>> print('H' in x) with the right operand equivalent to
10
it item is not in list True and assign the result to
>>> a[0]=20 or in sequence left operand. c=c/a
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module> 2 not in True if value is not >>> x="Hello 6 %= It takes modulus using c %= a is
found in list or in World" two operands and assign equivalent to
sequence, and false the result to left operand.

Page 7 of 23 Page 8 of 23 Page 9 of 23


c=c%a ['h', 'o', 'n'] Ans:
>>> list2[-7] 1)
7 **= Performs exponential c **= a is
(power) calculation on equivalent to
Traceback (most recent call last): >>> dict1={1:"Vijay",2:"Santosh",3:"Yogita"}
operators and assign File "<pyshell#76>", line 1, in <module> >>>print(dict1)
value to the left operand. c = c ** a list2[-7] {1: 'Vijay', 2: 'Santosh', 3: 'Yogita'}
IndexError: list index out of range
8 //= Performs exponential c //= a is ii)
(power) calculation on equivalent to List Slicing: Slicing is an operation that allows us to extract >>>dict1[2]="Shreyas"
operators and assign
c = c // a elements from units. The slicing feature used by Python to >>>print(dict1)
value to the left operand.
obtain a specific subset or element of the data structure {1: 'Vijay', 2: 'Shreyas', 3: 'Yogita'}
c) Explain indexing and slicing in list with example 4M: (2m for using the colon (:) operator.
Indexing: An individual item in the list can be referenced by indexing and 2m The slicing operator returns a subset of a list called slice by iii)
using an index, which is an integer number that indicates the for slicing) specifying two indices, i.e. start and end. >>>dict1.pop(1)
relative position of the item in the list. Syntax: list_variable[start_index:end_index] ‘Vijay'
There are various ways in which we can access the elements This will return the subset of the list starting from start_index >>>print(dict1)
of a list some as them are given below: to one index less than that of the endind {2: 'Shreyas', 3: 'Yogita'}
1. List Index: We can use the index operator [] to access an Example: For slicing list. b) Explain decision making statements If-else, if-elif-else with 4M (2m for if-
item in a list. Index starts from 0. So, a list having 5 elements >>> l1=([10,20,30,40,50]) example else and 2m for
will have index from 0 to 4. >>> l1[1:4] The if-else statement: if statements executes when the if-elif-else)
Example: For list index in list. [20, 30, 40] conditions following if is true and it does nothing when the
>>> list1=[10,20,30,40,50] >>>l1[2:5] condition is false. The if-else statement takes care of a true
>>> list1[0] [30,40,50] as well as false condition.
10 d) Write a program for importing module for addition and 4M (for correct Syntax-1: Or Syntax-2:
>>> list1[3:] # list[m:] will return elements indexed from mth subtraction of two numbers logic and If condition: If condition:
index to last index calculation.py: program) Statement(s) If_Block
[40, 50] def add(x,y): else: else:
>>>list1[:4] # list[:n] will return elements indexed from first return (x+y) Statement(s) else_Block
index to n-1th index def sub(x,y): Example:
[10, 20, 30, 40] return (x-y) i=20
>>> list1[1:3] # list[m:n] will return elements indexed from m if(i<15):
to n-1. operation.py: print(" less than 15")
[20, 30] import calculation else:
print("greater than 15")
>>> list1[5] print(calculation.add(1,2))
Traceback (most recent call last): print(calculation.sub(4,2))
output:
File "<pyshell#71>", line 1, in <module> Output: greater than 15
list1[5] 3 Concept Diagram:
IndexError: list index out of range 2
2. Negative Indexing: Python allows negative indexing for its
sequences. The index of −1 refers to the last item, −2 to the 4 Attempt any THREE of the following 12
second last item and so on. a) Write a program to create dictionary of student the 4M (2m for i),
Example: For negative indexing in list. includes their ROLL NO and NAME 1m for ii) and
>>> list2=['p','y','t','h','o','n'] i) Add three students in above dictionary 1m for iii))
>>> list2[-1] ii) Update name=’Shreyas’ of ROLL NO=2
'n' iii) Delete information of ROLL NO=1
>>> list2[-6]
'p'
>>> list2[-3:]

Page 10 of 23 Page 11 of 23 Page 12 of 23

c) Explain use of format() method with example 4M (2m for use special meaning to the return,finally,import,def
if-elif-else (ladder) statements: Here, a user can decide among The format() method formats the specified value(s) and insert and 2m for language
multiple options. The if statements are executed from the top them inside the string's placeholder. example) compiler/interpreter
down. As soon as one of the conditions controlling the if is true, The placeholder is defined using curly brackets: {}. Identifiers: names given to def square,num=20,
the statement associated with that if is executed, and the rest of The format() method returns the formatted string. different parts of program a_lst=[1,2,3];
the ladder is bypassed. If none of the conditions is true, then the Syntax like variables, functions, here square,num and a_lst are
final else statement will be executed. string.format(value1, value2...) object, class, names given to identifiers.
Syntax: different datatypes.
if (condition-1): Example: Literals/Constants: Data String: ‘Mayank‘,’abc‘,’anish‘;
statement #named indexes: items that have fixed values Numeric: 1,1.2,4,-3.95;
elif (condition-2): >>>txt1 = ("My name is {fname}, I'm {age}".format(fname = Boolean: True,False
statements "abc", age = 36)) Special literal None; meaning nothing
. >>>print(txt1) e) Write a program illustrating use of user defined package in 4M (2m for
. My name is abc, I'm 36 python defining
elif(condition-n): A package is a hierarchical file directory structure that defines a package and 2m
statements #numbered indexes: single Python application environment that consists of modules
>>>txt2 =( "My name is {0}, I'm {1}".format("xyz",36))
for import
else: and subpackages and sub-subpackages, and so on.
statements >>>print(txt2) package in
Packages allow for a hierarchical structuring of the module program)
My name is xyz, I'm 36 namespace using dot notation.
Example: Creating a package is quite straightforward, since it makes use of
Example: #empty placeholders: the operating system’s inherent hierarchical file structure.
i = 20 >>>txt3 = ("My name is {}, I'm {}".format("pqr",36)) Consider the following arrangement:
if (i == 10): >>>print(txt3)
print ("i is 10") My name is pqr, I'm 36
elif (i == 15): d) Explain building blocks of python 4M
print ("i is 15") Character set: All characters that python can recognize. The
elif (i == 20): below table illustrates the Python character set along with
print ("i is 20") examples. Here, there is a directory named pkg that contains two
else: character Set Examples modules, mod1.py and mod2.py. The contents of the modules
print ("i is not present") Letters: Upper case and A-Z,a-z are:
lower case english mod1.py
output: alphabets def m1():
i is 20 Digits: all digits 0-9 print("first module")
Special symbols space,+,-,**,*,%,//,/,==,!=,>,<
Concept Diagram: Whitespaces Blank space,tabs mod2.py
Other unicode characters All ASCII and Unicode characters def m2():
Tokens: Tokens in python are building blocks of the Python print("second module")
programming language. The role letters and words play for the
English language, Similar to role token play for a python If the pkg directory resides in a location where it can be found, you
programming language. can refer to the two modules with dot
Python has the following tokens: notation(pkg.mod1, pkg.mod2) and import them with the
1)keywords syntax:
2)identifiers
3)literals Syntax-1
a)String literals import <module_name>[, <module_name> ...]
b)Numeric literals Example:
c)Boolean Literals >>>import pkg.mod1, pkg.mod2
d)Special literal None >>> pkg.mod1.m1()
Tokens Example first module
Keywords: Words that are False,True,if,elif,else,for,
already defined and convey a while,pass,continue,lambda,

Page 13 of 23 Page 14 of 23 Page 15 of 23


Syntax-2: Method overloading is a concept in which a method in a class alternatives available in python that make it possible to call
from <module_name> import <name(s)> performs operations according to the parameters passed to the same method but with different number of arguments.
Example: it. c) Write a program to open a file in write mode and append 6M for any
>>> from pkg.mod1 import m1 As in other languages we can write a program having two some content at the end of file program with
>>> m1()
methods with same name but with different number of file1 = open("myfile.txt", "w") suitable logic
First module L = ["This is Delhi \n", "This is Paris \n", "This is London"]
arguments or order of arguments but in python if we will try
>>> file1.writelines(L)
to do the same we will get the following issue with method
overloading in Python: file1.close()
Syntax-3:
from <module_name> import <name> as <alt_name> # to calculate area of rectangle
def area(length, breadth): # Append-adds at last
Example:
# append mode
>>> from pkg.mod1 import m1 as module calc = length * breadth
file1 = open("myfile.txt", "a")
>>> module() print calc
first module #to calculate area of square # writing newline character
def area(size): file1.write("\n")
You can import modules with these statements as well: calc = size * size
from <package_name> import <modules_name>[, file1.write("Today")
print calc
<module_name> ...]
area(3) # without newline character
from <package_name> import <module_name> as <alt_name>
Example: area(4,5) file1.write("Tomorrow")
>>> from pkg import mod1 Output:
>>> mod1.m1() 9 file1 = open("myfile.txt", "r")
First module TypeError: area() takes exactly 1 argument (2 given) print("Output of Readlines after appending")
Python does not support method overloading, that is, it is print(file1.read())
not possible to define more than one method with the print()
5 Attempt any TWO of the following 12
same name in a class in Python. file1.close()
a) Write the output of the following 6M
i) >>> a=[2,5,1,3,6,9,7] (2m for each) This is because method arguments in python do not have a
type. A method accepting one argument can be called with Output:
>>> a[2:6]=[2,4,9,0]
an integer value, a string or a double as shown in next Output of Readlines after appending
>>> print(a)
example. This is Delhi
Output: [2, 5, 2, 4, 9, 0, 7]
class Demo: This is Paris
This is London
ii) >>> b=[“Hello”,”Good”] def method(self, a):
TodayTomorrow
>>> b.append(“python”) print(a)
>>>print(b) obj= Demo()
obj.method(50) 6 Attempt any TWO of the following 12
Output: ['Hello', 'Good', 'python']
obj.method('Meenakshi') a) Explain package Numpy with example 6M (3m for
iii) >>>t1=[3,5,6,7] output:
obj.method(100.2) • NumPy is the fundamental package for scientific explanation and
>>>print(t1[2]) >>>6
Output: computing with Python. NumPy stands for 3m for example)
>>>print(t1[-1]) >>>7
50 "Numerical Python". It provides a high-performance
>>>print(t1[2:]) >>>[6, 7]
Meenakshi multidimensional array object, and tools for working
>>>print(t1[:]) >>>[3, 5, 6, 7]
100.2 with these arrays.
b) Explain method overloading in python with example 6M (3m for
Same method works for three different data types. Thus, we • An array is a table of elements (usually numbers), all
Method overloading is the ability to define the method with explanation, 3m
cannot define two methods with the same name and same of the same type, indexed by a tuple of positive
the same name but with a different number of arguments for example)
number of arguments but having different type as shown in integers and represented by a single variable.
and data types.
With this ability one method can perform different tasks, the above example. They will be treated as the same NumPy's array class is called ndarray. It is also known
depending on the number of arguments or the types of the method. by the alias array.
arguments given. It is clear that method overloading is not supported in python • In NumPy arrays, the individual data items are called
but that does not mean that we cannot call a method with elements. All elements of an array should be of the
different number of arguments. There are a couple of

Page 16 of 23 Page 17 of 23 Page 18 of 23

same type. Arrays can be made up of any number of >>> type(arr) car1.disp_price()
dimensions. <class 'numpy.ndarray'> Output:
• In NumPy, dimensions are called axes. Each >>> print("No. of dimension: ", arr.ndim) Name= Maruti
dimension of an array has a length which is the total No. of dimension: 2 Price=$ 2000
number of elements in that direction. >>> print("Shape of array: ", arr.shape)
• The size of an array is the total number of elements Shape of array: (2, 3) Example 2: Inheritance using constructor.
contained in an array in all the dimension. The size of >> >print("size of array: ", arr.size) class Vehicle: #parent class
NumPy arrays are fixed; once created it cannot be size of array: 6 def __init__(self,name):
changed again. >>> print("Type of elements in array: ", arr.dtype) self.name=name
• Numpy arrays are great alternatives to Python Lists. Type of elements in array: int32 def display(self):
Some of the key advantages of Numpy arrays are that >>> print("No of bytes:", arr.nbytes) print("Name= ",self.name)
they are fast, easy to work with, and give users the No of bytes: 24 class Category(Vehicle): #derived class
opportunity to perform calculations across entire b) Write a program to implement the concept of inheritance 6M for any def __init__(self,name,price):
arrays. in python suitable Vehicle.__init__(self,name)
• A one dimensional array has one axis indicated by • In inheritance objects of one class procure the example of # passing data to base class constructor
Axis-0. That axis has five elements in it, so we say it properties of objects of another class. inheritance self.price=price
has length of five. • Inheritance provide code usability, which means that def disp_price(self):
• A two dimensional array is made up of rows and some of the new features can be added to the code print("Price=$ ",self.price)
columns. All rows are indicated by Axis-0 and all while using the existing code. car1=Category("Maruti",2000)
columns are indicated by Axis-1. If Axis-0 in two • The mechanism of designing or constructing classes car1.display()
dimensional array has three elements, so its length it from other classes is called inheritance. car1.disp_price()
three and Axis-1 has six elements, so its length is six. • The new class is called derived class or child class and car2=Category("BMW",5000)
the class from which this derived class has been car2.display()
Execute Following command to install numpy in window, inherited is the base class or parent class. car2.disp_price()
Linux and MAC OS: • In inheritance, the child class acquires the properties Output:
python -m pip install numpy and can access all the data members and functions Name= Maruti
To use NumPy you need to import Numpy: defined in the parent class. A child class can also Price=$ 2000
import numpy as np # alias np provide its specific implementation to the functions Name= BMW
of the parent class. Price=$ 5000
Using NumPy, a developer can perform the following Syntax: c) Explain Try-except block used in exception handling in 6M (3m for
operations: class A: python with example explanation and
1. Mathematical and logical operations on arrays. # properties of class A • In Python, exceptions can be handled using a try 3m for program)
2. Fourier transforms and routines for shape manipulation. class B(A): statement. A try block consisting of one or more
3. Operations related to linear algebra. # class B inheriting property of class A statements is used by programmers to partition code
4. NumPy has in-built functions for linear algebra and # more properties of class B that might be affected by an exception.
random number generation • A critical operation which can raise exception is
Example 1: Inheritance without using constructor. placed inside the try clause and the code that handles
Example: class Vehicle: #parent class exception is written in except clause.
For NumPy with array object. name="Maruti" • The associated except blocks are used to handle any
>>> import numpy as np def display(self): resulting exceptions thrown in the try block. That is
>>> a=np.array([1,2,3]) # one dimensional array print("Name= ",self.name) we want the try block to succeed and if it does not
>>> print(a) class Category(Vehicle): #derived class succeed, we want to control to pass to the catch
[1 2 3] price=2000 block.
>>> arr=np.array([[1,2,3],[4,5,6]]) # two dimensional array def disp_price(self): • If any statement within the try block throws an
>>> print(arr) print("Price=$",self.price) exception, control immediately shifts to the catch
[[1 2 3] car1=Category() block. If no exception is thrown in the try block, the
[4 5 6]] car1.display() catch block is skipped.

Page 19 of 23 Page 20 of 23 Page 21 of 23


MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
WINTER – 2023 EXAMINATION
• There can be one or more except blocks. Multiple except IOError: Model Answer – Only for the Use of RAC Assessors
except blocks with different exception names can be print ("Error: can\'t find file or read data")
chained together. else: Subject Name: Programming with Python 22616
Subject Code: 22616
• The except blocks are evaluated from top to bottom print ("Written content in the file successfully")
Important Instructions to examiners:
in the code, but only one except block is executed for fh.close()
1) The answers should be examined by key words and not as word-to-word as given in the model answer scheme.
each exception that is thrown. 2) The model answer and the answer written by candidate may vary but the examiner may try to assess the understanding
• The first except block that specifies the exact level of the candidate.
exception name of the thrown exception is executed. 3) The language errors such as grammatical, spelling errors should not be given more Importance (Not applicable for
If no except block specifies a matching exception subject English and Communication Skills.
name then an except block that does not have an 4) While assessing figures, examiner may give credit for principal components indicated in the figure. The figures drawn
exception name is selected, if one is present in the by candidate and model answer may vary. The examiner may give credit for any equivalent figure drawn.
code. 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.
• For handling exception in Python, the exception
handler block needs to be written which consists of
6) In case of some questions credit may be given by judgement on part of examiner of relevant answer based on
candidate’s understanding.
set of statements that need to be executed according 7) For programming language papers, credit may be given to any other program based on equivalent concept.
to raised exception. There are three blocks that are 8) As per the policy decision of Maharashtra State Government, teaching in English/Marathi and Bilingual (English +
used in the exception handling process, namely, try, Marathi) medium is introduced at first year of AICTE diploma Programme from academic year 2021-2022. Hence if
except and finally. 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
1. try Block: A set of statements that may cause error during answer.
runtime are to be written in the try block.
2. except Block: It is written to display the execution details Q. Sub Answer Marking
to the user when certain exception occurs in the program. No. Q. Scheme
The except block executed only when a certain type as N.
exception occurs in the execution of statements written in
the try block. 1 Attempt any FIVE of the following: 10 M
3. finally Block: This is the last block written while writing an Enlist applications for python programming.
a) 2M
exception handler in the program which indicates the set of
statements that many use to clean up to resources used by Ans  Google's App Engine web development framework uses Python as an application Any two
the program. language. application,
 Maya, a powerful integrated 3D modeling and animation system, provides a Python One application
Syntax: scripting API. for 1 M each
try:  Linux Weekly News, published by using a web application written in Python.
D the operations here  Google makes extensive use of Python in its Web Search Systems.
......................  The popular YouTube video sharing service is largely written in Python
except Exception1: programming.
If there is Exception1, then execute this block.  The NSA uses Python for cryptography and intelligence analysis.
except Exception2:  iRobot uses Python programming to develop commercial and military robotic devices.
If there is Exception2, then execute this block.  The Raspberry Pi single-board computer promotes Python programming as its
...................... educational language.
else:  Nextflix and Yelp have both documented the role of Python in their software
infrastructures.
If there is no exception then execute this block.
 Industrial Light and Magic, Pixar and others uses Python in the production of
animated movies.
Example: For try-except clause/statement.
 Desktop GUI Applications
try:  Image Processing Applications
fh = open("testfile", "w")  Scientific and Numeric Applications
fh.write("This is my test file for exception handling!!")  Audio and Video Based Applications
 3D CAD Applications
Page 22 of 23 Page 23 of 23
Page No: 1 | 20

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________ __________________________________________________________________________________________________
 Software Development  Namespaces prevent conflicts between classes, methods and objects with the 3. insert() Method: We can insert one single item at a desired location by using the method
 Web Applications same name that might have been written by different people. insert() or insert multiple items by squeezing it into an empty slice of a list.
b) Write the use of elif keyword in python. 2M  A namespace is a system to have a unique name for each and every object in Example: Program for insert() method.
>>> list1=[10, 20]
Python. An object might be a variable or a method. Python itself maintains a
>>>list1
Ans elif' stands for 'else if' and is used in Python programming to test multiple conditions. Correct namespace in the form of a Python dictionary. [10,20]
The if statements are executed from the top down. As soon as one of the conditions controlling explanation 2  A namespace in python is a collection of names. So, a namespace is essentially >>> list1.insert(1,30)
the if is true, the statement associated with that if is executed, and the rest of the ladder is M a mapping of names to corresponding objects. >>> list1
bypassed. If none of the conditions is true, then the final else statement will be executed.
f) State the use of read() and readline () functions in python file handling. 2M [10, 30, 20]

c) Describe the Role of indentation in python. 2M Ans 1. read([n]) Method: read() 1 M and
The read method reads the entire contents of a file and returns it as a string, if number readline() 2. Attempt any THREE of the following: 12 M
Ans  Indentation refers to the spaces at the beginning of a code line. Correct Role 2 of bytes are not given in the argument. If we execute read(3), we will get back the first
1M a) Explain membership and identity operators in Python. 4M
 Generally, four whitespaces are used for indentation and is preferred over tabs. M three characters of the file.
 Where in other programming languages the indentation in code is for readability only, Example: for read( ) method. Ans Membership Operators: Membership
(example is not
the indentation in Python is very important. f=open("sample.txt","r") The membership operators in Python are used to find the existence of a particular operator 2 M
mandatory)
 Indentation helps to convey a better structure of a program to the readers. It is used to print(f.read(5)) # read first 5 data element in the sequence, and used only with sequences like string, tuple, list, and Identity
clarify the link between control flow constructs such as conditions or loops, and code print(f.read()) # read rest of the file dictionary etc.
contained within and outside of them. operator 2 M
Membership operators are used to check an item or an element that is part of a string,
 Python uses indentation to indicate a block of code. 2. readline([n]) Method: a list or a tuple. A membership operator reduces the effort of searching an element in
Example: The readline() method just output the entire line whereas readline(n) outputs at most the list.
if 5 > 2: n bytes of a single line of a file. It does not read more than one line. Once, the end of Python provides ‘in’ and ‘not in’ operators which are called membership operators
print("Five is greater than two!") file is reached, we get empty string on further reading. and used to test whether a value or variable is in a sequence.
d) Define Data Hiding concept? Write two advantages of Data Hiding. 2M Example: For readline ( ) method. Operator Description Example
f=open("sample.txt","r")
Ans  Data hiding is a concept which underlines the hiding of data or information from the Any relevant print(f.readline()) # read first line followed by\n in True if value is found in list or in >>> x="Hello World"
user. Definition 1 M, print(f.readline(3)) sequence, and false it item is not >>> print('H' in x)
 Data hiding is a software development technique specifically used in Object-Oriented print(f.readline()) in list or in sequence True
any two
Programming (OOP) to hide internal object details (data members). g) Explain two ways to add objects / elements to list. 2M not in True if value is not found in list >>> x="Hello World"
 Data hiding includes a process of combining the data and functions into a single unit Advantages 1
or in sequence, and false it item is >>> print("Hello" not in x)
to conceal data within a class by restricting direct access to the data from outside the M in list or in sequence. False
class. Ans 1)append method: The append() method adds an element to the end of a list. We can insert 1 Method for 1
a single item in the list data time with the append(). M (any two
Example: For append() method. Identity Operators: Sometimes, in Python programming a need to compare the
Advantages of Data Hiding methods) memory address of two objects; this is made possible with the help of the identity
>>> list1=[10,20,30]
 Data hiding ensures exclusive data access to class members and protects object operator. Identity operators are used to check whether both operands are same or not.
>>> list1
integrity by preventing unintended or intended changes.
[10, 20, 30] Python provides ‘is’ and ‘is not’ operators which are called identity operators and both
 Data hiding is also known as information hiding. An object's attributes may or may >>> list1.append(40) # add element at the end of list
not be visible outside the class definition.
are used to check if two values are located on the same part of the memory. Two
>>> list1 (example is not
 Data hiding also minimizes system complexity for increase robustness by limiting variables that are equal does not imply that they are identical.
[10, 20, 30, 40] mandatory) Operator Description Example
interdependencies between software requirements.
 The objects within the class are disconnected from irrelevant data.
 It heightens the security against hackers that are unable to access confidential data. is Return true, if the variables on either side >>> a=3
2. extend() Method: The extend() method extends a list by appending items. We can add of the operator point to the same object >>> b=3
 It helps to prevent damage to volatile data by hiding it from the public. several items using extend() method. and false otherwise. >>> print(a is b)
 A user outside from the organization cannot attain the access to the data. Example: Program for extend() method. True
 Within the organization/ system only specific users get the access. This allows better >>>list1=[10, 20, 30, 40] is not Return false, if the variables on either >>> a=3
operation. >>>list1 side of the operator point to the same >>> b=3
e) State use of namespace in python. 2M [10, 20, 30, 40] object and true otherwise. >>> print(a is not b)
>>> list1.extend([60,70]) #add elements at the end of list False
Ans  Namespaces bring you three advantages: they group names into logical Correct/relevant >>> list1
use 2 M [10, 20, 30, 40, 60, 70] b) Write python program to display output like. 4M
containers, they prevent clashes between duplicate names, and third, they
provide context to names.
Page No: 2 | 20 Page No: 3 | 20 Page No: 4 | 20
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________ __________________________________________________________________________________________________
2 >>> list1.pop(2) Ans Like, C, C++, and Java, a file in Python programming can be opened in various modes Listing of
4 6 8 7 depending upon the purpose. For that, the programmer needs to specify the mode modes- 1 M
10 12 14 16 18 10 list.remove(item) It deletes the given item >>> list1 whether read 'r', write 'w', or append 'a' mode. Apart from this, two other modes exist, and explain ant
Ans a=2 Correct or any from the list. [1, 2, 3, 4, 5] which specify to open the file in text mode or binary mode. 2- 3 M
for i in range(1,5): relevant Logic/ >>> list1.remove(3) 1. The text mode returns strings while reading from the file. The default is reading in
for j in range(i): any other >>> list1
text mode.
print(a,end="\t") suitable [1, 2, 4, 5]
a+=2 2. The binary mode returns bytes and this is the mode to be used when dealing with
Program 4 M 11 list.reverse() It reverses the position >>> list1
print() (index number) of the items [1, 2, 3, 4, 5] non-text files like image or executable files.
in the list. >>> list1.reverse() The text and binary modes are used in conjunction with the r, w, and a modes. The list
c) Explain four built-in list functions. 4M >>> list1 of all the modes used in Python are given in following table:
[5, 4, 3, 2, 1] Sr. No. Mode Description
Ans Sr. No. Function Description Example 12 list.sort([func]) It sorts the elements inside >>> list1
1 len(list) It returns the length of the >>> list1 the list and uses compare [1, 3, 2, 5, 4] 1 r Opens a file for reading only. The file pointer is placed
Any 4 functions function if provided. >>> list1.sort() at the beginning of the file. This is the default mode.
list. [1, 2, 3, 4, 5]
>>> len(list1) 4 M, 1 M each >>> list1
5 [1, 2, 3, 4, 5] 2 rb Opens a file for reading only in binary format. The file
2 max(list) It returns the item that has >>> list1 d) Write python program using module, show how to write and use module by 4M pointer is placed at the beginning of the file. This is the
the maximum value in a [1, 2, 3, 4, 5] importing it. default mode.
list. >>> max(list1)
5 Ans For creating a module write following code and save it as p1.py Write module 2
#p1.py M and Import 2 3 r+ Opens a file for both reading and writing. The file
3 sum(list) Calculates sum of all the >>>list1
elements of list. [1, 2, 3, 4, 5] def add(a, b): M pointer placed at the beginning of the file.
>>>sum(list1) "This function adds two numbers and return the result"
15 result = a + b 4 rb+ Opens a file for both reading and writing in binary
4 min(list) It returns the item that has >>> list1 return result format. The file pointer placed at the beginning of the
the minimum value in a list. [1, 2, 3, 4, 5] file.
>>> min(list1)
def sub(a, b):
1 5 w Opens a file for writing only. Overwrites the file if the
"This function subtract two numbers and return the result"
5 list(seq) It converts a tuple into a >>> list1
list. [1, 2, 3, 4, 5] result = a – b file exists. If the file does not exist, creates a new file
>>> list(list1) return result for writing.
[1, 2, 3, 4, 5]
6 list.append(item) It adds the item to the end >>> list1 Import the definitions inside a module: 6 wb Opens a file for writing only in binary format.
of the list. [1, 2, 3, 4, 5] Overwrites the file if the file exists. If the file does not
>>> list1.append(6) import p1 exist, creates a new file for writing.
>>> list1 print(p1.add(10,20))
[1, 2, 3, 4, 5, 6] print(p1.sub(20,10)) 7 w+ Opens a file for both writing and reading. Overwrites
7 list.count(item) It returns number of times >>> list1
the item occurs in the list. [1, 2, 3, 4, 5, 6, 3] the existing file if the file exists. If the file does not
>>> list1.count(3)
Output: exist, creates a new file for reading and writing.
2 30
8 list.extend(seq) It adds the elements of the >>> list1 10 8 wb+ Opens a file for both writing and reading in binary
sequence at the end of the [1, 2, 3, 4, 5] format. Overwrites the existing file if the file exists. If
list. >>> list2
['A', 'B', 'C']
the file does not exist, creates a new file for reading and
>>> list1.extend(list2) 3. Attempt any THREE of the following: 12 M writing.
>>> list1
[1, 2, 3, 4, 5, 'A', 'B', 'C'] a) Describe various modes of file object? Explain any two in detail. 4M 9 a Opens a file for appending. The file pointer is at the end
9 list.pop(item=list[- It deletes and returns the >>> list1 of the file if the file exists.
1]) last element of the list. [1, 2, 7, 3, 4, 5, 3]
>>> list1.pop()
3
Page No: 5 | 20 Page No: 6 | 20 Page No: 7 | 20

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________ __________________________________________________________________________________________________
That is, the file is in the append mode. If the file does Else Statement: The else block just after for/while is executed only when the loop is NOT It is clear that method overloading is not supported in python but that does not mean
not exist, it creates a new file for writing. terminated by a break statement. The else keyword in a for loop specifies a block of code to that we cannot call a method with different number of arguments. There are a couple
be executed when the loop is finished: of alternatives available in python that make it possible to call the same method but
10 ab Opens a file for appending in binary format. The file with different number of arguments.
Example:
pointer is at the end of the file if the file exists. That is, for i in range(1, 4):
the file is in the append mode. If the file does not exist, print(i)
Method Overriding: Overriding is the ability of a class to change the implementation
else: # Executed because no break in for of a method provided by one of its base class. Method overriding is thus a strict part
it creates a new file for writing.
print("Finally Exit”) of the inheritance mechanism. To override a method in the base class, we must define
Output: a new method with same name and same parameters in the derived class. Overriding
11 a+ Opens a file for both appending and reading. The file
1 is a very important part of OOP since it is the feature that makes inheritance exploit
pointer is at the end of the file if the file exists. The file 2 its full power. Through method overriding a class may "copy" another class, avoiding
opens in the append mode. If the file does not exist, it 3 duplicated code, and at the same time enhance or customize part of it.
creates a new file for reading and writing. Finally Exit
c) T = ('spam, Spam', SPAM!', 'SaPm') 4M Example: For method overriding.
12 ab+ Opens a file for both appending and reading in binary print (T [2]) class A: # parent class
format. The file pointer is at the end of the file if the print (T[-2]) "Parent Class"
print (T[2:])
file exists. The file opens in the append mode. If the file def display(self):
print (List (T))
does not exist, it creates a new file for reading and Input
print ('This is base class.')
Ans Each Print
writing. T = ('spam’, ‘Spam', ‘SPAM!', 'SaPm') class B(A): #derived class
Statement/
"Child/Derived class"
output for 1 M
13 t Opens in text mode (default). Python statement Output def display(self):
print (T [2]) SPAM! print ('This is derived class.')
14 b Opens in binary mode print (T[-2]) SPAM! obj = B() # instance of child
print (T[2:]) [‘SPAM!', 'SaPm'] obj.display() # child calls overridden method
15 + Opens a file for updating (reading and writing). print (list (T)) ['spam', 'Spam', 'SPAM!', 'SaPm'] Output:
This is derived class.

d) Explain method overloading and overriding in python. 4M


b) Explain use of Pass and Else keyword with for loops in python. 4M Ans Method Overloading: Method overloading is the ability to define the method with the same Method 4. Attempt any THREE of the following: 12 M
name but with a different number of arguments and data types. With this ability one method Overloading
Ans Pass Statement: It is used when a statement is required syntactically but we do not Pass for 2 M can perform different tasks, depending on the number of arguments or the types of the a) Explain different functions or ways to remove key : value pair from 4M
want any command or code to execute. A pass statement in Python also refers to as a and Else for 2 arguments given. Method overloading is a concept in which a method in a class performs 2M
Dictionary.
will statement. The pass statement is a null operation; nothing happens when it executes. M operations according to the parameters passed to it. Python does not support method and Overriding
The pass is also useful in places where your code will eventually go, but has not been written overloading, that is, it is not possible to define more than one method with the same name in 2M pop(): We can remove a particular item in a dictionary by using the method pop(). Any two
Ans
yet. a class in Python. This is because method arguments in python do not have a type. A method This method removes as item with the provided key and returns the value. functions, 2m
Syntax: pass accepting one argument can be called with an integer value, a string or a double as shown in
Example: For pass statement. Example: each
next example.
for i in range(1,11): class Demo:
>>> squares
if i%2==0: # check if the number is even def method(self, a): {1: 1, 2: 4, 3: 9, 4: 16}
pass # (No operation) print(a) >>> squares.pop(2) # remove a particular item
else: obj= Demo( ) 4
print("Odd Numbers: ",i) obj.method(50) >>> squares
Output: obj.method('Meenakshi') {1: 1, 3: 9, 4: 16}
Odd Numbers: 1 obj.method(100.2)
Odd Numbers: 3 Output: Popitem(): The method, popitem() can be used to remove and return an arbitrary item
Odd Numbers: 5 50 (key, value) form the dictionary.
Odd Numbers: 9 Meenakshi Example:
Odd Numbers: 7
100.2 >>> squares={1:1,2:4,3:9,4:16,5:25}
>>> squares
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Page No: 8 | 20 Page No: 9 | 20 Page No: 10 | 20
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________ __________________________________________________________________________________________________
>>> print(squares.popitem()) # remove an arbitrary item d) WAP to read contents of first.txt file and write same content in second.txt 4M
(5, 25) file.
>>> squares
{1: 1, 2: 4, 3: 9, 4: 16} Ans with open('first.txt', 'r') as f: # Open the first file for reading Correct logic
contents = f.read() # Read the contents of the file program/any
Clear(): All the items can be removed at once using the clear() method. suitable
Example: with open('second.txt', 'w') as f: # Open the second file for writing program 4 M
f.write(contents) # Write the contents of the first file to the second file
>>> squares
{1: 1, 4: 16}
>>> squares.clear() # removes all items
 A one dimensional array has one axis indicated by Axis-0. That axis has five 5. Attempt any TWO of the following: 12 M
>>> squares
{} elements in it, so we say it has length of five. a) Explain any four set operations with example. 6M
 A two dimensional array is made up of rows and columns. All rows are
Del(): We can also use the del keyword to remove individual items or the entire indicated by Axis-0 and all columns are indicated by Axis-1. If Axis-0 in two Ans Set Operations: Each operation
dictionary itself. dimensional array has three elements, so its length it three and Axis-1 has six 1. Set Union: The union of two sets is the set of all the elements of both the sets without -1 ½ M
Example: elements, so its length is six. duplicates. You can use the ‘|’ operator to find the union of a Python set.
>>> squares >>> first_set = {1, 2, 3}
{1: 1, 3: 9, 4: 16} Execute Following command to install numpy in window, Linux and MAC OS: >>> second_set = {3, 4, 5}
>>> del squares[3] # delete a particular item >>> first_set.union(second_set)
python -m pip install numpy {1, 2, 3, 4, 5}
>>> squares
>>> first_set | second_set # using the ‘|’ operator
{1: 1, 4: 16} To use NumPy you need to import Numpy:
{1, 2, 3, 4, 5}
import numpy as np # alias np
Using NumPy, a developer can perform the following operations: 2. Set Intersection: The intersection of two sets is the set of all the common elements of
b) Explain Numpy package in detail. 4M 1. Mathematical and logical operations on arrays. both the sets. You can use the ‘&’ operator to find the intersection of a Python set.
2. Fourier transforms and routines for shape manipulation. >>> first_set = {1, 2, 3, 4, 5, 6}
Ans  NumPy is the fundamental package for scientific computing with Python. Suitable 3. Operations related to linear algebra. >>> second_set = {4, 5, 6, 7, 8, 9}
NumPy stands for "Numerical Python". It provides a high-performance explanation 4 4. NumPy has in-built functions for linear algebra and random number generation. >>> first_set.intersection(second_set)
multidimensional array object, and tools for working with these arrays. M {4, 5, 6}
 An array is a table of elements (usually numbers), all of the same type, indexed c) Explain seek ( ) and tell ( ) function for file pointer manipulation in 4M >>> first_set & second_set # using the ‘&’ operator
by a tuple of positive integers and represented by a single variable. NumPy's python with example. {4, 5, 6}
array class is called ndarray. It is also known by the alias array.
3. Set Difference
 In NumPy arrays, the individual data items are called elements. All elements Ans seek(): In python programming, within file handling concept seek() function is used to For seek()
The difference between two sets is the set of all the elements in first set that are not present
of an array should be of the same type. Arrays can be made up of any number shift/change the position of file object to required position. By file object we mean a cursor. method: 2 M
And it’s cursor, who decides from where data has to be read or write in a file. in the second set. You would use the ‘–‘ operator to achieve this in Python.
of dimensions. and for Tell() >>> first_set = {1, 2, 3, 4, 5, 6}
 In NumPy, dimensions are called axes. Each dimension of an array has a length Syntax: method 2 M
f.seek(offset, fromwhere) >>> second_set = {4, 5, 6, 7, 8, 9}
which is the total number of elements in that direction. where offset represents how many bytes to move fromwhere, represents the position from >>> first_set.difference(second_set)
 The size of an array is the total number of elements contained in an array in all where the bytes are moving. {1, 2, 3}
the dimension. The size of NumPy arrays are fixed; once created it cannot be Example: >>> first_set - second_set # using the ‘-‘ operator
changed again. f = open("demofile.txt", "r") {1, 2, 3}
>>> second_set - first_set
 Numpy arrays are great alternatives to Python Lists. Some of the key f.seek(4) #sets Reference point to fourth index position from the beginning
print(f.readline()) {8, 9, 7}
advantages of Numpy arrays are that they are fast, easy to work with, and give
users the opportunity to perform calculations across entire arrays. 4. Set Symmetric Difference: The symmetric difference between two sets is the set of all
tell(): tell() returns the current position of the file pointer from the beginning of the file.
Syntax: file.tell() the elements that are either in the first set or the second set but not in both. You have the
 Fig. shows the axes (or dimensions) and lengths of two example arrays; (a) is choice of using either the symmetric_difference() method or the ^ operator to do this in
Example:
a one-dimensional array and (b) is a two-dimensional array. f = open("demofile.txt", "r") Python.
# points at the start >>> first_set = {1, 2, 3, 4, 5, 6}
print(f.tell()) >>> second_set = {4, 5, 6, 7, 8, 9}
>>> first_set.symmetric_difference(second_set)
{1, 2, 3, 7, 8, 9}

Page No: 11 | 20 Page No: 12 | 20 Page No: 13 | 20

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________ __________________________________________________________________________________________________
>>> first_set ^ second_set # using the `^` operator structures to learn in Python are List (list), Dictionary (dict), Tuple (tuple), and Set Sets: Sets in Python are the non-duplicative data structure. That means they
{1, 2, 3, 7, 8, 9} (set). can only store one of an element. Sets are declared with curly braces like
b) Explain building blocks of python. 6M Strings dictionaries, but do not contain ‘:’ in them. The example code shows how to
Strings in Python are assigned with single or double quotations. As in many turn a list into a set, access set elements by index, add to a set, and remove
Ans 1) Python Identifiers: Variable name is known as identifier. Any 6 building other programming languages, characters in strings may be accessed as if from a set.
To name an identifier following are the rules: blocks=6M accessing an array. In the example below we’ll assign a string to a variable,
 The first character of the variable must be an alphabet or underscore ( _ ). # we can turn a list into a set
access the first element, check for a
 All the characters except the first character may be an alphabet of lower-case(a-z), x = ['a', 'a', 'b', 'c', 'c']
substring, and check the length of the string.
upper-case (A-Z), underscore or digit (0-9). x = set(x)
 Identifier name must not contain any white-space, or special character (!, @, #, %, ^,
x = 'abcd'
&, *).
 Identifier name must not be similar to any keyword defined in the language. o Numbers: Integers and Floats in Python are both Number types. They can
5) Control structures: Control structures are used to determine the flow of execution
Identifier names are case sensitive for example my name, and MyName is not the interact with each other, they can be used in all four operations. In the
of a Python program. Examples of control structures in Python include if-else
same. example code we’ll explore how these numbers can interact.
statements, for and while loops, and try-except blocks.
Eg: a,b,c=5,10,15 x = 2.5
y=2
6) Functions: Functions are reusable blocks of code that perform specific tasks. In
2) Reserved Words
The following list shows the Python keywords. These are reserved words and cannot use Python, functions are defined using the def keyword.
them as constant or variable or any other identifier names. All the Python keywords contain Boolean: Boolean variables in Python are either True or False. They will also
lowercase letters only. return True for 1 and False for 0. The example shows how to assign either 7) Modules: Python modules are files that contain Python code and can be imported
True or False to a variable in Python into other Python programs to reuse code and simplify development.
x = True
y = False 8) Packages: Packages are collections of related Python modules that can be installed
and imported together. Packages are commonly used in Python for organizing and
distributing libraries and tools.
Lists: Lists in Python are represented with brackets. Like characters in a string, c) Write a program illustrating use of user defined package in python. 6M
the elements in a list can be accessed with brackets. Lists can also be
enumerate‘d on to return both the index and the element. We’ll go over Ans # student.py Create package:
enumerate when we cover for loops in Python. The example code shows how class Student: 2m
to declare lists, print elements in them, add to them, and remove from them. def __init__(self, student):
self.name = student['name'] Importing
x = [10, 25, 63, 104] self.gender = student['gender'] packages: 2m
y = ['a', 'q', 'blah'] self.year = student['year']
Logic: 2m
3) Indentation: Python provides no braces to indicate blocks of code for class and function Dictionaries: Dictionaries in Python are a group of key-value pairs. def get_student_details(self): (Any
definitions or flow control. Blocks of code are denoted by line indentation, which is Dictionaries are declared with curly braces and their entries can be accessed return f"Name: {self.name}\nGender: {self.gender}\nYear: {self.year}"
compulsory.
Similar/Suitable
in two ways, a) with brackets, and b) with .get. The example code shows how other
The number of spaces in the indentation is variable, but all statements within the block
we can access items in a dictionary. logic/program
must be indented the same amount. For example –
# faculty.py can consider)
_dict = { class Faculty:
if True: 'a': 'Sally sells sea shells',
print "True" def __init__(self, faculty):
'b': 'down by the seashore' self.name = faculty['name']
else:
print "False" } self.subject = faculty['subject']

Thus, in Python all the continuous lines indented with same number of spaces would form def get_faculty_details(self):
Tuples: Tuples is an immutable sequence in Python. Unlike lists, you can’t move
a block. return f"Name: {self.name}\nSubject: {self.subject}"
objects out of order in a Tuple. Tuples are declared with parenthesis and must
contain a comma (even if it is a tuple of 1). The example below shows how to add
4) Python Types: The basic types in Python are String (str), Integer (int), Float tuples, get a tuple from a list, and return information about it. # testing.py
(float), and Boolean (bool). There are also built in data structures to know when you x = (a, b) # importing the Student and Faculty classes from respective files
learn Python. These data structures are made up of the basic types, you can think of from student import Student
them like Legos, the data structures are made out of these basic types. The core data from faculty import Faculty
Page No: 14 | 20 Page No: 15 | 20 Page No: 16 | 20
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________ __________________________________________________________________________________________________
Ans class Animal: #super class Any other add():
# creating dicts for student and faculty suitable Adds an element to the set. If an element is already exist in the set, then it does not
student_dict = {'name' : 'ABC', 'gender': 'Male', 'year': '3'} # attribute and method of the parent class program can add that element.
faculty_dict = {'name': 'XYZ', 'subject': 'Programming'} name = "" consider Example:
def eat(self): s = {'g', 'e', 'k', 's'}
# creating instances of the Student and Faculty classes print("I can eat") # adding f into set s
student = Student(student_dict) s.add('f')
# inherit from Animal Class creation:
faculty = Faculty(faculty_dict) print('Set after updating:', s)
class Dog(Animal): sub(2 M class 2m
# getting and printing the student and faculty details Inherit one output:
print(student.get_student_details()) # new method in subclass Set after updating: {'s', 'f', 'e', 'g', 'k'}
class to another:
print() def display(self):
2m
print(faculty.get_faculty_details()) # access name attribute of superclass using self discard():
print("My name is ", self.name) Logic: 2m Removes the element from the set
Example:
Output : # create an object of the subclass s = {'g', 'e', 'k', 's'}
Name: ABC labrador = Dog() print('Set before discard:', s)
Gender: Male
Year: 3
s.discard('g')
# access superclass attribute and method print('\nSet after discard g:', s)
labrador.name = "Rohu"
Name: XYZ
Subject: Programming
labrador.eat() Output:
# call subclass method Set before discard: {'s', 'e', 'k', 'g'}
Set after discard g: {'s', 'e', 'k'}
labrador.display()
6. Attempt any TWO of the following: 12 M
Output: remove():
a) Write a program to create class student with Roll no. and Name and 6M I can eat Removes the specified element from the set. If the specified element not found, raise
display its contents My name is Rohu an error.
Example:
Ans class Student: Create Class: s = {'g', 'e', 'k', 's'}
def __init__(self, name, rollno): 3m c) List and explain any four built-in functions on set. 6M
print('Set before remove:', s)
self.name = name s.remove('e')
self.rollno = rollno Display Ans Built-in Functions with Set Listing: 2m
Method: 3m add() print('\nSet after remove e:', s)
discard() Explanation of
def __str__(self): any two Output:
return f"{self.name}({self.rollno})" copy()
remove() function: 4m Set before remove: {'s', 'k', 'e', 'g'}
clear() Set after remove e: {'s', 'k', 'g'}
(2 M each)
s1 = Student("ABC", 32) union()
print(s1) difference() clear():
intersection() Removes all elements from the set
Output: discard() Example:
ABC 32 issubset() s = {'g', 'e', 'k', 's'}
issuperset() print('Set before clear:', s)
b) Write program to implement concept of inheritance in python. 6M pop() s.clear()
update() print('\nSet after clear:', s)
symmetric_difference() Output:
Set before clear: {'g', 'k', 's', 'e'}
Set after clear: set()

Page No: 17 | 20 Page No: 18 | 20 Page No: 19 | 20

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous) (Autonomous)

m
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________ __________________________________________________________________________________________________
SUMMER – 2023 EXAMINATION • Python provides ‘in’ and ‘not in’ operators which are called membership

sb

sb
copy(): Returns a shallow copy of the set
Example: Model Answer – Only for the Use of RAC Assessors operators and used to test whether a value or variable is in a sequence.
s = {'g', 'e', 'k', 's'}

te

te
p=s.copy() Subject Name: Programming with Python Subject Code: 22616 c) Write down the output of the following Python code 2M

al

al
print("original set:",s) >>>indices-['zero','one','two',' three,' four, five']
print("Copied set:",p) Important Instructions to examiners: XXXXX i) >>>indices[:4]

lc

lc
1) The answers should be examined by key words and not as word-to-word as given in the model answer scheme.
ii) >>>indices[:-2]
2) The model answer and the answer written by candidate may vary but the examiner may try to assess the

le

le
Output:
understanding level of the candidate. Ans Output as follows: 1 M for
original set: {'k', 's', 'g', 'e'}

ar

ar
3) The language errors such as grammatical, spelling errors should not be given more Importance (Not applicable for i) >>>indices[:4] each
Copied set: {'k', 's', 'g', 'e'} subject English and Communication Skills.
[zero, one, two, three] correct

.c

.c
4) While assessing figures, examiner may give credit for principal components indicated in the figure. The figures
ii) >>>indices[:-2] output
drawn by candidate and model answer may vary. The examiner may give credit for any equivalent figure drawn.

o
Union():The set.union() method returns a new set with distinct elements from all the 5) Credits may be given step wise for numerical problems. In some cases, the assumed constant values may vary and [zero, one, two, three]
given sets.

m
there may be some difference in the candidate’s answers and model answer.
Example: 6) In case of some questions credit may be given by judgement on part of examiner of relevant answer based on d) Describe any two data conversion function. 2M
nums1 = {1, 2, 2, 3, 4, 5} candidate’s understanding.
nums2 = {4, 5, 6, 7, 7, 8} Ans • int(x [,base]): Converts x to an integer. base specifies the base if x is a Any 2
7) For programming language papers, credit may be given to any other program based on equivalent concept.
distinct_nums = nums1.union(nums2) string. Conversion
8) As per the policy decision of Maharashtra State Government, teaching in English/Marathi and Bilingual (English +
print("The union of two sets is: ", distinct_nums) Marathi) medium is introduced at first year of AICTE diploma Programme from academic year 2021-2022. Hence if Example: x=int('1100',base=2)=12 function
the students in first year (first and second semesters) write answers in Marathi or bilingual language (English • long(x [,base]): Converts x to a long integer. base specifies the base if x is 2M
Output: +Marathi), the Examiner shall consider the same and assess the answer based on matching of concepts with model a string.
The union of two sets is: {1, 2, 3, 4, 5, 6, 7, 8} answer. Example: x=long(‘123’base=8)=83L
Difference():The set.difference() method returns the new set with the unique elements • float(x): Converts x to a floating point number.
Q. Sub Answer Marking
that are not in the other set passed as a parameter. Example: x=float('123.45')=123.45
No. Q. Scheme
Example: N. • complex(real[,imag]) : Creates a complex number.
nums1 = {1, 2, 2, 3, 4, 5} Example: x=complex(1,2) = (1+2j)
nums2 = {4, 5, 6, 7, 8, 8} 1 Attempt any FIVE of the following: 10 M • str(x): Converts object x to a string representation.
nums3 = nums1.difference(nums2)
a) List features of Python. 2M Example: x=str(10) = ‘10’
nums4 = nums2.difference(nums1)
• repr(x): Converts object x to an expression string
print("nums1 - nums2: ", nums3)
Ans Features of Python are listed below: Any 2, Example: x=repr(3) = 3
print("nums2 - nums1: ", nums4)
• Easy to Learn and Use 1 M each • repr(x): Evaluates a string and returns an object.
Output: • Interpreted Language Example: x=eval('1+2') = 3
nums1 - nums2: {1, 2, 3} • Interactive Mode • tuple(s): Converts s to a tuple
nums2 - nums1: {8, 6, 7} • Free and Open Source Example:
• Platform Independence/Cross-platform Language/Portable x=tuple('123') = ('1', '2', '3')
Intersection():The set.intersection() method returns a new set with the elements that
• Object-Oriented Language x=tuple([123]) = (123,)
are common in the given sets.
Example: • Extensible • list(s): Converts s to a list
x = {"apple", "banana", "cherry"} Example:
b) Describe membership operators in python 2M
y = {"google", "microsoft", "apple"} x=list('123') = ['1', '2', '3']
z = x.intersection(y) Ans • The membership operators in Python are used to find the existence of a particular 2 M for x=list(['12'] = ['12']
print(z) element in the sequence, and used only with sequences like string, tuple, list, proper • set(s): Converts s to a set
dictionary etc. explanation Example:
Output: • Membership operators are used to check an item or an element that is part of a x=set('Python')
apple
string, a list or a tuple. A membership operator reduces the effort of searching an = {'y', 't', 'o', 'P', 'n', 'h'}
element in the list. • dict(d): Creates a dictionary. d must be a sequence of (key, value) tuples.

Page No: 20 | 20 Page No: 1 | 24 Page No: 2 | 24


MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous) (Autonomous)

m
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________ __________________________________________________________________________________________________
Syntax: os.mkdir(“newdir”)

sb

sb

sb
Example: Output:
dict={'id':'11','name':'vijay'}
Example: i=1

te

te

te
print(dict)
i=2
={'id': '11', 'name': 'vijay'} >>> import os

al

al

al
i=3
• chr(x): Converts an integer to a character. i=4

lc

lc

lc
Example: x=chr(65) = ‘A’ >>> os.mkdir("testdir") i=6

le

le

le
unichr(x): Converts an integer to a Unicode character i=7
g) Describe Multiline comment in python. 2M
Example: x=unichr(65) =u’A’ i=8

ar

ar

ar
• ord(x): Converts a single character to its integer value. i=9
Ans • In some situations, multiline documentation is required for a program. If we have 2 M for i=10

.c

.c

.c
Example: x=ord('A')= 65 proper
comments that extend multiple lines, one way of doing it is to use hash (#) in the b) Explain creating Dictionary and accessing Dictionary Elements with 4M
• hex(x): Converts an integer to a hexadecimal string. explanation

om

om

om
beginning of each line. Another way of doing this is to use quotation marks, either example.
Example: x=hex(12) = 0xc ''' or """.
• oct(x): Converts an integer to an octal string. • Similarly, when it sees the triple quotation marks ''' it scans for the next ''' and Ans Creating Dictionary Creating
Example: x=oct(8) = 0o10 ignores any text in between the triple quotation marks. Dictionary
The simplest method to create dictionary is to simply assign the pair of key:values explanation
e) With neat example explain default constructor concept in Python. 2M Example: For multiline comment. to the dictionary using operator (=). with example
• There are two ways for creation of dictionary in python. 2 M,
Ans The default constructor is simple constructor which does not accept any arguments. It’s Explanation '''This is first python program 1. We can create a dictionary by placing a comma-separated list of key:value Accessing
definition has only one argument which is a reference to the instance being constructed. 1 M,
Example Print is a statement''' pairs in curly braces{}. Each key is separated from its associated value by a Dictionary
Example 1: Display Hello message using default constructor. 1M colon: Element with
Example: For creating a dictionary using { }. example 2 M
class Student: >>> dict1={} #Empty dictionary
2. Attempt any THREE of the following: 12 M
>>> dict1
def _ _init_ _(self):
a) Describe Keyword "continue" with example. 4M {}
print("This is non parametrized constructor") >>> dict2={1:"Orange", 2:"Mango", 3:"Banana"} #Dictionary with
Ans • The continue statement in Python returns the control to the beginning of the while Explanation integer keys
def show(self,name): loop. 2M,
>>> dict2
• The continue statement rejects all the remaining statements in the current iteration Example
{1: 'Orange', 2: 'Mango', 3: 'Banana'}
print("Hello",name) of the loop and moves the control back to the top of the loop. 2M
>>> dict3={"name":"vijay", 1:[10,20]} #Dictionary with mixed keys
s1 = Student() Syntax: continue >>> dict3
{'name': 'vijay', 1: [10, 20]}
s1.show("Student1") Example: For continue statement.
2. Python provides a build-in function dict() for creating a dictionary
i=0
Example: Creating directory using dict().
Output: while i<10: >>> d1=dict({1:"Orange",2:"Mango",3:"Banana"})
>>> d2=dict([(1,"Red"),(2,"Yellow"),(3,"Green")])
This is non parametrized constructor i=i+1 >>> d3=dict(one=1, two=2, three=3)
Hello Student1 >>> d1
if i==5:
{1: 'Orange', 2: 'Mango', 3: 'Banana'}
f) Describe mkdir() function. 2M >>> d2
continue
{1: 'Red', 2: 'Yellow', 3: 'Green'}
Ans • We can make a new directory using the mkdir() method. Explanation print("i= ",i) >>> d3
• This method takes in the path of the new directory. If the full path is not specified, 2M {'one': 1, 'two': 2, 'three': 3}
the new directory is created in the current working directory.

Page No: 3 | 24 Page No: 4 | 24 Page No: 5 | 24

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous) (Autonomous)
m

m
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________ __________________________________________________________________________________________________
sb

sb

sb
Accessing Values in a Dictionary 15 '0b1010'
• We can access the items of a dictionary by following ways: with the prefix 0b.
1. Referring to its key name, inside square brackets([]).
te

te

te
• min(list)
Example: For accessing dictionary items [ ] using. • bool()
It returns the item that has the minimum value in a list.
al

al

al
>>> dict1={'name':'vijay','age':40} The bool() function returns the boolean value of a specified object.
>>> dict1['name'] Example:
lc

lc

lc
>>> list1 Example:
'vijay'
>>> bool(1)
le

le

le
>>> dict1['adr'] [1, 2, 3, 4, 5]
Traceback (most recent call last): >>> min(list1) True
ar

ar

ar
File "<pyshell#79>", line 1, in <module> 1
dict1['adr'] • exp()
.c

.c

.c
KeyError: 'adr' The method exp() returns returns exponential of x: ex.
• list(seq)
o

o
>>> x: This is a numeric expression.
Here, if we refer to a key that is not in the dictionary, you’ll get an It converts a tuple into a list.
m

m
exception. This error can be avoided by using get() method. Example: Example:
>>> math.exp(1)
2. Using get() method returns the value for key if key is in the dictionary, else >>> list1 2.718281828459045
None, so that this method never raises a KeyError. [1, 2, 3, 4, 5] >>>
Example: For accessing dictionary elements by get(). >>> list(list1)
>>> dict1={'name':'vijay','age':40} [1, 2, 3, 4, 5]
>>> dict1.get('name') • abs(n) d) Write a Python program to find the factorial of a number provided by the 4M
'vijay' It returns the absolute value of a number. user.
Example:
c) Explain any four Python's Built-in Function with example. 4M >>> abs(10) Ans num=int(input("Enter Number:")) Correct
10 fact=1 program
Ans • len(list) Any 4 Built- if num< 0:
in function 4M
It returns the length of the list. • all() print("Sorry, factorial does not exist for negative numbers")
Example: with example The all() function returns True if all items in an iterable are true, otherwise it elif num == 0:
>>> list1 4M returns False. print("The factorial of 0 is 1")
[1, 2, 3, 4, 5] Example: else:
>>> len(list1) >>> x=[True, True, True] for i in range(1,num + 1):
5 >>> all(x) fact=fact*i
• max(list) True print("The factorial of ",num," is ",fact)
It returns the item that has the maximum value in a list
Example: • any() Output:
>>> list1 The any() function returns True if any item in an iterable are true, otherwise it Enter Number: 5
[1, 2, 3, 4, 5] returns False. If the iterable object is empty, the any() function will return False. The factorial of 5 is 120
>>> max(list1) Example:
5 >>> x=[True, False, True]
>>> any(x)
3. Attempt any THREE of the following: 12 M
• sum(list) True
Calculates sum of all the elements of list. a) Write a python program to input any two tuples and interchange the tuple 4M
Example: • bin() variables.
>>>list1 The bin() function returns the binary version of a specified integer. The result
will always start >>> bin(10) Ans def interchange_tuples(tup1, tup2): Any correct
[1, 2, 3, 4, 5]
Example: programming
>>>sum(list1)

Page No: 6 | 24 Page No: 7 | 24 Page No: 8 | 24


MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous) (Autonomous)

m
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________ __________________________________________________________________________________________________

sb

sb

sb
new_tup1 = tup2 logic 4 M result = a & b specified number of positions. Zeros are shifted in from the left side.
new_tup2 = tup1 print(result) # Output: 2 (binary: 0010) Example:

te

te

te
return new_tup1, new_tup2 2) Bitwise OR (|): Performs a bitwise OR operation on the corresponding bits of two a = 10 # binary: 1010

al

al

al
numbers. Each bit of the output is 0 if the corresponding bits of both operands are
# Input two tuples result = a >> 2

lc

lc

lc
0; otherwise, it is 1.

le

le

le
tuple1 = tuple(input("Enter the elements of the first tuple (separated by commas): Example: print(result) # Output: 2 (binary: 10)
").split(","))

ar

ar

ar
a = 10 # binary: 1010 c) With neat example differentiate between readline () and readlines ( ) 4M
tuple2 = tuple(input("Enter the elements of the second tuple (separated by commas): functions in file-handling.

.c

.c

.c
").split(",")) b = 6 # binary: 0110
Ans readline(): This method reads a single line from the file and returns it as a string. It moves readline()

om

om

om
result = a | b the file pointer to the next line after reading. If called again, it will read the subsequent explanation
# Interchange the tuples print(result) # Output: 14 (binary: 1110) line. for 1 M and
Example for
result_tuple1, result_tuple2 = interchange_tuples(tuple1, tuple2) 3) Bitwise XOR (^): Performs a bitwise XOR (exclusive OR) operation on the # Open the file in read mode 1M
corresponding bits of two numbers. Each bit of the output is 1 if the file = open("example.txt", "r")
corresponding bits of the operands are different; otherwise, it is 0. and
readlines()
# Display the result # Read the first line
Example: explanation
line1 = file.readline() for 1 M and
print("Interchanged tuples:") a = 10 # binary: 1010 Example for
print("Tuple 1:", result_tuple1) print(line1) 1M
b = 6 # binary: 0110
print("Tuple 2:", result_tuple2) result = a ^ b
output: # Read the second line
print(result) # Output: 12 (binary: 1100)
Enter the elements of the first tuple (separated by commas): 10,20 line2 = file.readline()
4) Bitwise NOT (~): Performs a bitwise NOT operation on a single operand, which
inverts all the bits. It returns the complement of the given number. print(line2)
Enter the elements of the second tuple (separated by commas): 30,40
Example:
Interchanged tuples:
a = 10 # binary: 1010 # Close the file
Tuple 1: ('30', '40')
result = ~a file.close()
Tuple 2: ('10', '20')
print(result) # Output: -11 (binary: -1011) readlines(): This method reads all lines from the file and returns them as a list of strings.
b) Explain Bitwise operator in Python with appropriate example. 4M
Each line is an individual element in the list. It reads the entire file content and stores it in
5) Bitwise left shift (<<): Shifts the bits of the left operand to the left by a specified memory.
Ans Bitwise operators available in Python: Any four number of positions. Zeros are shifted in from the right side.
operator
1) Bitwise AND (&): Performs a bitwise AND operation on the corresponding bits Example:
(Each for 1 Example:
of two numbers. Each bit of the output is 1 if the corresponding bits of both M) # Open the file in read mode
operands are 1; otherwise, it is 0. a = 10 # binary: 1010
file = open("example.txt", "r")
Example: result = a << 2
a = 10 # binary: 1010 print(result) # Output: 40 (binary: 101000)
# Read all lines
b = 6 # binary: 0110 6) Bitwise right shift (>>): Shifts the bits of the left operand to the right by a

Page No: 9 | 24 Page No: 10 | 24 Page No: 11 | 24

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous) (Autonomous)
m

m
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________ __________________________________________________________________________________________________
sb

sb

sb
lines = file.readlines() # Access the attributes using the self parameter is placed at the beginning of the file. This is the default mode.
3 r+ Opens a file for both reading and writing. The file pointer placed at
print(my_car.make) # Output: Toyota the beginning of the file.
te

te

te
# Close the file print(my_car.model) # Output: Corolla 4 rb+ Opens a file for both reading and writing in binary format. The
al

al

al
file pointer placed at the beginning of the file.
file.close() print(my_car.year) # Output: 2022 5 w Opens a file for writing only. Overwrites the file if the file
lc

lc

lc
exists. If the file does not exist, creates a new file for writing.
le

le

le
# Print each line 6 wb Opens a file for writing only in binary format. Overwrites the
file if the file exists. If the file does not exist, creates a new file
ar

ar

ar
for line in lines: # Call the method using the self parameter
for writing
7 w+ Opens a file for both writing and reading. Overwrites the
.c

.c

.c
print(line) car_info = my_car.get_info()
existing file if the file exists. If the file does not exist, creates a
o

o
d) Describe 'Self Parameter with example. 4M print(car_info) # Output: Make: Toyota, Model: Corolla, Year: 2022 new file for reading and writing.
m

m
8 wb+ Opens a file for both writing and reading in binary format.
Ans In Python, the self parameter is a convention used in object-oriented programming (OOP) Explanation Overwrites the existing file if the file exists. If the file does not
to refer to the instance of a class within the class itself. It allows you to access the 2 M and exist, creates a new file for reading
# Call the method that does not require any additional parameters
attributes and methods of the class from within its own methods. The name self is not a
example 2 and writing
keyword in Python, but it is widely adopted and recommended as a convention. my_car.start_engine() # Output: Engine started!
M 9 a Opens a file for appending. The file pointer is at the end of the
Example: file if the file exists. That is, the file is in the append mode. If
the file does not exist, it creates a new file for writing.
class Car: 4. Attempt any THREE of the following: 12 M 10 ab Opens a file for appending in binary format. The file pointer is
at the end of the file if the file exists. That is, the file is in the
def __init__(self, make, model, year): a) Differentiate between list and Tuple. 4M append mode. If the file does not exist, it creates a new file for
self.make = make writing
Ans Any 4 11 a+ Opens a file for both appending and reading. The file pointer
self.model = model correct point is at the end of the file if the file exists. The file opens in the
List Tuple 4M append mode. If the file does not exist, it creates a new file for
self.year = year reading and writing.
Lists are mutable Tuples are immutable
12 ab+ Opens a file for both appending and reading in binary format.
The implication of iterations is Time- The implication of iterations is The file pointer is at the end of the file if the file exists. The file
def get_info(self): consuming comparatively Faster opens in the append mode. If the file does not exist, it creates
a new file for reading and writing.
info = f"Make: {self.make}, Model: {self.model}, Year: {self.year}" The list is better for performing A Tuple data type is appropriate for
13 t Opens in text mode (default).
operations, such as insertion and deletion. accessing the elements
return info 14 b Opens in binary mode.
Lists consume more memory Tuple consumes less memory as 15 + Opens a file for updating (reading and writing).
compared to the list c) Write a program to show user defined exception in Python. 4M
def start_engine(self): Lists have several built-in methods Tuple does not have many built-in Ans class MyException(Exception): Any correct
methods. logic
print("Engine started!") def __init__(self, message): program 4 M
Unexpected changes and errors are more In a tuple, it is hard to take place.
likely to occur self.message = message
# Create an instance of the Car class
b) Explain any four file modes in Python. 4M
my_car = Car("Toyota", "Corolla", 2022) # Function that raises the custom exception
Ans Sr. No. Mode Description 1 Mode for 1
1 r Opens a file for reading only. The file pointer is placed at the M def divide_numbers(a, b):
beginning of the file. This is the default mode.
2 rb Opens a file for reading only in binary format. The file pointer
Page No: 12 | 24 Page No: 13 | 24 Page No: 14 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous) (Autonomous)

m
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________ __________________________________________________________________________________________________

sb

sb

sb
if b == 0: copying its definition into each program. print("The string is not a palindrome.")
raise MyException("Division by zero is not allowed!") • In Python we can put definitions in a file and use them in a script or in an interactive output:

te

te

te
instance of the interpreter. Such a file is called a module.
return a / b Enter a string: madam

al

al

al
Use of module in python :
The string is a palindrome.

lc

lc

lc
Code organization: Modules allow you to organize related code into separate files,

le

le

le
# Main program making it easier to navigate and maintain large projects. Enter a string: abc

ar

ar

ar
try: Code reusability: Modules can be imported and reused in multiple programs, enabling The string is not a palindrome.
code reuse and reducing duplication.

.c

.c

.c
num1 = int(input("Enter the numerator: ")) b) Write a Python program to calculate sum of digit of given number using 6M
Encapsulation: Modules provide a way to encapsulate code and hide the implementation function.

om

om

om
num2 = int(input("Enter the denominator: "))
details, allowing users to focus on the functionality provided by the module.
Ans def calculate_digit_sum(number): Any correct
Name spacing: Modules help avoid naming conflicts by providing a separate namespace logic
result = divide_numbers(num1, num2) for the names defined within the module. # Convert the number to a string program 6M.

print("Result:", result) num_str = str(number)

5. Attempt any TWO of the following: 12 M # Initialize a variable to store the sum

except MyException as e: a) Write a Python Program to check if a string is palindrome Or not. 6M digit_sum = 0

print("Exception:", e.message) # Iterate over each character in the string


Ans def is_palindrome(string): Any correct
logic for digit in num_str:
Note: Any correct program of user defined exception can be considered. # Remove whitespace and convert to lowercase program 6M.
Output: # Convert the character back to an integer and add it to the sum
string = string.replace(" ", "").lower()
Enter the numerator: 10 digit_sum += int(digit)
# Reverse the string
Enter the denominator: 0 # Return the sum of the digits
reversed_string = string[::-1]
Exception: Division by zero is not allowed! return digit_sum
# Check if the original and reversed strings are the same
Enter the numerator: 10 # Test the function
if string == reversed_string:
Enter the denominator: 5 input_number = int(input("Enter a number: "))
return True
Result: 2.0 sum_of_digits = calculate_digit_sum(input_number)
else:
print("Sum of digits:", sum_of_digits)
d) Explain Module and its use in Python. 4M return False
output:
Ans Modules are primarily the (.py) files which contain Python programming code defining Explanation # Test the function
functions, class, variables, etc. with a suffix .py appended in its file name. 2 M and use Enter a number: 123
2M input_string = input("Enter a string: ")
• A file containing .py python code is called a module. Sum of digits: 6
if is_palindrome(input_string):
• If we want to write a longer program, we can use file where we can do editing, c) Write a Python Program to accept values from user in a list and find the 6M
correction. This is known as creating a script. As the program gets longer, we may want print("The string is a palindrome.")
largest number and smallest number in a list.
to split it into several files for easier maintenance. else:
Ans list = [] Any correct
• We may also want to use a function that you’ve written in several programs without logic
Page No: 15 | 24 Page No: 16 | 24 Page No: 17 | 24

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous) (Autonomous)
m

m
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________ __________________________________________________________________________________________________
sb

sb

sb
num = int(input('How many numbers: ')) program 6M set1 = {1, 2, 3} numbers.clear()

for n in range(num): set2 = {2, 3, 4} print(numbers) # Output: set()


te

te

te
numbers = int(input('Enter number ')) intersection_set = set1.intersection(set2) 7) isdisjoint():
al

al

al
The isdisjoint() method in Python's set class is used to check whether two sets
list.append(numbers) print(intersection_set) # Output: {2, 3}
lc

lc

lc
have any common elements. It returns True if the sets are disjoint (i.e., they have
no common elements), and False otherwise.
le

le

le
print("Maximum element in the list is :", max(list), "\nMinimum element in the list is :", 3) Difference:
Example:
min(list)) # Example 1
ar

ar

ar
Difference operation on two sets set1 and set2 returns all the elements which are
present on set1 but not in set2. set1 = {1, 2, 3, 4}
output:
.c

.c

.c
set2 = {5, 6, 7}
Example: set3 = {3, 4, 5}
How many numbers: 5
o

o
m

m
set1 = {1, 2, 3, 4, 5} print(set1.isdisjoint(set2)) # True, no common elements
Enter number 10
set2 = {3, 4} print(set1.isdisjoint(set3)) # False, both sets have elements 3 and 4
Enter number 20
difference_set = set1.difference(set2)
Enter number 30 # Example 2
print(difference_set) # Output: {1, 2, 5} fruits = {"apple", "banana", "orange"}
Enter number 40
colors = {"red", "green", "blue"}
4) add(element):
Enter number 50
This function adds an element to a set. print(fruits.isdisjoint(colors)) # True, no common elements
Maximum element in the list is : 50
Example:
Minimum element in the list is : 10 # Example 3
fruits = {"apple", "banana", "cherry"} setA = {1, 2, 3}
fruits.add("orange") setB = {4, 5, 6}
6. Attempt any TWO of the following: 12 M
print(fruits) # Output: {'apple', 'banana', 'cherry', 'orange'} print(setA.isdisjoint(setB)) # True, no common elements
a) Explain any six set function with example. 6M
8) pop():method in Python's set class is used to remove and return an arbitrary
Ans 1) union():Return a new set containing the union of two or more sets 1 function element from the set. Since sets are unordered collections, there is no guarantee
5) remove(element): on which element will be popped.
for 1 M each
Example: Example:
This function removes an element from a set.
fruits = {"apple", "banana", "orange", "grape"}
set1 = {1, 2, 3}
Example:
set2 = {3, 4, 5} # Remove and return an arbitrary element from the set
numbers = {1, 2, 3, 4, 5} popped_element = fruits.pop()
union_set = set1.union(set2)
numbers.remove(3)
print(popped_element) # Output: an arbitrary element from the set
print(union_set) # Output: {1, 2, 3, 4, 5} print(fruits) # Output: the modified set after popping an element
print(numbers) # Output: {1, 2, 4, 5}
2) Intersection:
6) clear(): 9) update():The update() method in Python's set class is used to update a set by
Intersection operation performed on two sets returns all the elements which are adding elements from another iterable or set. It modifies the set in place by adding
This function removes all elements from a set, making it an empty set. all the elements from the iterable or set specified.
common or in both the sets.
Example: Example:
Example: set1 = {1, 2, 3}
numbers = {1, 2, 3, 4, 5} set2 = {3, 4, 5}

Page No: 18 | 24 Page No: 19 | 24 Page No: 20 | 24


MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous) (Autonomous)

m
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________ __________________________________________________________________________________________________

sb

sb

sb
set1.update(set2) # Read and set student information Example:
student.read_student_info() # Base class

te

te

te
print(set1) # Output: {1, 2, 3, 4, 5}
class Animal:

al

al

al
b) Design a class student with data members : name, roll no., department, 6M
# Print student information def __init__(self, name):

lc

lc

lc
mobile no. Create suitable methods for reading and printing student
information.

le

le

le
student.print_student_info() self.name = name

ar

ar

ar
Ans class Student: Any correct output:
logic

.c

.c

.c
def __init__(self): program 6 Enter student name: raj def speak(self):
M

om

om

om
self.name = "" Enter roll number: 11 print("Animal speaks")
self.roll_no = "" Enter department: computer
self.department = "" Enter mobile number: 123456 # Derived class inheriting from Animal
self.mobile_no = "" Student Information: class Dog(Animal):
Name: raj def speak(self):
def read_student_info(self): Roll Number: 11 print("Dog barks")
self.name = input("Enter student name: ") Department: computer
self.roll_no = input("Enter roll number: ") Mobile Number: 123456 # Derived class inheriting from Animal
self.department = input("Enter department: ") c) With suitable example explain inheritance in Python. 6M class Cat(Animal):
self.mobile_no = input("Enter mobile number: ") Ans In inheritance objects of one class procure the properties of objects of another class. Explanation def speak(self):
Inheritance provide code usability, which means that some of the new features can be 3 M and
print("Cat meows")
added to the code while using the existing code. The mechanism of designing or Correct
def print_student_info(self): constructing classes from other classes is called inheritance. example 3 M

print("Student Information:") • The new class is called derived class or child class and the class from which this # Create instances of derived classes
derived class has been inherited is the base class or parent class.
print("Name:", self.name) dog = Dog("Buddy")
• In inheritance, the child class acquires the properties and can access all the data
print("Roll Number:", self.roll_no) members and functions defined in the parent class. A child class can also provide its cat = Cat("Whiskers")
specific implementation to the functions of the parent class.
print("Department:", self.department)
Syntax:
print("Mobile Number:", self.mobile_no) # Call the speak method of the derived classes
class A:
dog.speak() # Output: Dog barks
# properties of class A
# Create an instance of the Student class cat.speak() # Output: Cat meows
class B(A):
student = Student()
# class B inheriting property of class A
# more properties of class B

Page No: 21 | 24 Page No: 22 | 24 Page No: 23 | 24

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
m

(ISO/IEC - 27001 - 2013 Certified)


__________________________________________________________________________________________________
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
sb

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

WINTER – 2024 EXAMINATION WINTER – 2024 EXAMINATION


al

Model Answer – Only for the Use of RAC Assessors Model Answer – Only for the Use of RAC Assessors
lc

Subject: Programming with Python Subject Code: 22616 Subject: Programming with Python Subject Code: 22616
le

Important Instructions to examiners: b) List membership operators in Python. 2M


ar

1) The answers should be examined by key words and not as word-to-word as given Ans. Membership Operators: The membership operators in Python are Each
in the model answer scheme. used to find the existence of a particular element in the sequence and operator 1M
.c

2) The model answer and the answer written by candidate may vary but the examiner used only with sequences like string, tuple, list, dictionary etc.
may try to assess the understanding level of the candidate.
o

3) The language errors such as grammatical, spelling errors should not be given more
Sr. Operator Description Example
m

Importance (Not applicable for subject English and Communication Skills).


4) While assessing figures, examiner may give credit for principal components No
indicated in the figure. The figures drawn by candidate and model answer may 1 in True if value is >>> x="Hello World"
vary. The examiner may give credit for any equivalent figure drawn. found in list or in >>> print('H' in x)
5) Credits may be given step wise for numerical problems. In some cases, the sequence, and false True
assumed constant values may vary and there may be some difference in the it item is not in list
candidate’s answers and model answer. or in sequence
6) In case of some questions credit may be given by judgement on part of examiner 2 not in True if value is not >>> x="Hello World"
of relevant answer based on candidate’s understanding. found in list or in >>> print("Hello" not
7) For programming language papers, credit may be given to any other program sequence, and false in x) False
based on equivalent concept.
if item is in list or in
8) As per the policy decision of Maharashtra State Government, teaching in
English/Marathi and Bilingual (English + Marathi) medium is introduced at first year sequence.
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 c) Compare list and Tuple 2M
assess the answer based on matching of concepts with model answer. Ans. List Tuple
Lists are mutable Tuples are immutable Any two
Q. Sub Answer Marking Lists consume more memory Tuple consume less memory as correct
No Q.N. Scheme differences
compared to the list 1M each
1. Attempt any FIVE of the following: 10M Lists have several built-in Tuple does not have many
a) List features of Python 2M methods built-in methods
Ans.  Easy to Learn and Use Any four
The unexpected changes and In tuple, it is hard to take place
features
 Interactive Mode ½M each errors are more likely to occur
 Expressive Language In tuple
 Interpreted Language The List has the variable The tuple has the fixed length
length
 Cross-platform Language
Lists can be used to store Tuples are used to store only
 Portable homogeneous and heterogeneous elements.
 Free and Open Source heterogeneous elements
 Object-Oriented Language List iteration is slower and is Tuple iteration is faster.
 Extensible time consuming.
 Large Standard Library

Page 1 / 23 Page 2 / 23
Page No: 24 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)

WINTER – 2024 EXAMINATION WINTER – 2024 EXAMINATION WINTER – 2024 EXAMINATION


Model Answer – Only for the Use of RAC Assessors Model Answer – Only for the Use of RAC Assessors Model Answer – Only for the Use of RAC Assessors

Subject: Programming with Python Subject Code: 22616 Subject: Programming with Python Subject Code: 22616 Subject: Programming with Python Subject Code: 22616

d) List different object oriented features supported by Python 2M • a: open an existing file for append operation. It won‟t override
Ans. The main object-oriented features supported by Python:- Listing any existing data. Syntax:
 Classes four
• r+: To read and write data into the file. The previous data in the file if condition1:
features ½
 Objects M each will be overridden.
# Code block to execute if condition1 is True
 Encapsulation • w+: To write and read data. It will override existing data.
elif condition2:
 Inheritance # Code block to execute if condition1 is False and condition2 is
• a+: To append and read data from the file. It won‟t override existing True
 Polymorphism
 Abstraction
data. else:
2. Attempt any THREE of the following: 12M # Code block to execute if both condition1 and condition2 are
e) State how to perform comments in Python 2M False
a) Explain decision making statements if-else, if-elif-else with 4M
Ans. Single line comment: Single-line comments are created simply by Correct
example. Explanation
beginning a line with the hash (#) character, and they are explanation of each Example:
of each 1M Ans. Decision-making statements in Python allow the execution of specific
automatically terminated by the end of line. statement
age = 25
blocks of code based on conditions. Python provides several with
Example:
constructs for decision-making if age < 13:
# print is a statement print(„Hello Python‟) example 2M
Multi line comment: Python multi-line comment is a piece of text print("You are a child.")
if-else Statement elif 13 <= age <= 19:
enclosed in a delimiter (""") Triple quotation marks.
The if-else statement is used to test a condition. If the condition is
Example: print("You are a teenager.")
True, the code inside the if block is executed. If the condition is
""" Multi-line comment used elif 20 <= age <= 59:
False, the code inside the else block is executed.
print("Python Comments") """ print("You are an adult.")
or To add a multiline comment you could insert a # for each line:
Syntax: else:
Example:
if condition: print("You are a senior.")
#This is a comment
# Code block to execute if the condition is True
#written in
else: b) Describe any four methods of list in python. 4M
#more than just one line print("Hello, World!")
# Code block to execute if the condition is False Ans. Four commonly used methods of lists in Python: Description
f) Define class and object 2M Example: of each
Ans. Note: Any other relevant definition shall be considered Correct age = 16 1. append(): Adds a single item to the end of the list. method 1M
Class: A class is a user-defined blueprint or prototype from which definition of if age >= 18: Syntax:
each 1M
objects are created. Classes provide a means of bundling data and print("You are eligible to vote.") list.append(item)
functionality together. else: Example:
Object: An object is an instance of a class that has some attributes print("You are not eligible to vote.") fruits = ['apple', 'banana', 'cherry']
and behavior. Objects can be used to access the attributes of the class.
fruits.append('orange') # Adds 'orange' to the end of the list
if-elif-else Statement print(fruits)
g) List different modes of opening file in Python 2M The if-elif-else statement is used when there are multiple conditions
Ans. Modes for opening file: Any two
to check. Python evaluates each if or elif condition in sequence. If
correct
• r: open an existing file for a read operation. modes 1M one of the conditions evaluates to True, the corresponding block of 2. remove():Removes the first occurrence of a specified element
• w: open an existing file for a write operation. If the file already each code is executed, and the rest are skipped. If none of the if or elif from the list.
contains some data then it will be overridden. conditions are True, the code inside the else block is executed. Syntax:
list.remove(item)

Page 3 / 23 Page 4 / 23 Page 5 / 23

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)

WINTER – 2024 EXAMINATION WINTER – 2024 EXAMINATION WINTER – 2024 EXAMINATION


Model Answer – Only for the Use of RAC Assessors Model Answer – Only for the Use of RAC Assessors Model Answer – Only for the Use of RAC Assessors

Subject: Programming with Python Subject Code: 22616 Subject: Programming with Python Subject Code: 22616 Subject: Programming with Python Subject Code: 22616

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


Example: Consider the following arrangement:  'r+': Read and Write (file must exist) Explanation
fruits = ['apple', 'banana', 'cherry', 'banana']  'w+': Write and Read (creates a new file or truncates an of any two
fruits.remove('banana') # Removes the first occurrence of 'banana' existing file) 1M each
print(fruits)  'a+': Append and Read (adds content to the end of the file)

3. pop() : Removes and returns an item at a specified index from the r' (Read Mode)
Here, there is a directory named pkg that contains two modules,
list. If no index is provided, it removes and returns the last item. Opens the file for reading only. The file must already exist, and an
mod1.py and mod2.py. The contents of the modules are:
Syntax: error (FileNotFoundError) will be raised if the file does not exist.
mod1.py
list.pop(index) # Removes and returns the item at the given index Example:
def m1():
list.pop() # Removes and returns the last item try:
print("first module")
Example: file = open('example.txt', 'r') # Opens the file for reading
mod2.py
fruits = ['apple', 'banana', 'cherry'] content = file.read() # Reads the entire content of the file
def m2():
popped_item = fruits.pop(1) # Removes and returns the item at index print(content)
print("second module")
1 except FileNotFoundError:
If the pkg directory resides in a location where it can be found, you
print(fruits) # List after removal print("File not found!")
can refer to the two modules with dot
print(popped_item) # The removed item finally:
notation(pkg.mod1, pkg.mod2) and import them with the syntax:
4. sort() : Sorts the items of the list in ascending order (by default). It file.close() # Always close the file after use
Syntax-1
can also sort in descending order by passing an argument to the
import <module_name>[, <module_name> ...] 'w' (Write Mode)
reverse parameter.
Example: Opens the file for writing. If the file already exists, it overwrites the
Syntax:
>>>import pkg.mod1, pkg.mod2 file (erases its content). If the file does not exist, it is created.
list.sort()
>>> pkg.mod1.m1() Example:
Example:
first module with open('example.txt', 'w') as file: # Opens for writing, creates file
numbers = [5, 3, 8, 1, 2]
Syntax-2: if it doesn't exist
numbers.sort() # Sorts the list in ascending order
from <module_name> import <name(s)> file.write("Hello, World!") # Writes to the file
print(numbers)
Example: 3. Attempt any THREE of the following: 12M
>>> from pkg.mod1 import m1 a) Explain identity and assignment operators with example 4M
c) Write a program illustrating use of user defined package in 4M >>> m1()
2M for
Ans. Identity operators in Python are used to compare the memory 2M for
Python. first module addresses of two objects, determining whether two variables or identity and
Ans. defining 2M for
A package is a hierarchical file directory structure that defines a package objects reference the same memory location. There are two primary
d) Describe various modes of file object? Explain any two in detail. 4M assignment
single Python application environment that consists of modules and identity operators in Python.
2M for
Ans.  r': Read (default mode) operators
subpackages and sub-subpackages, and so on. Packages allow for a  'w': Write (creates a new file or truncates an existing file) Description
importing
hierarchical structuring of the module namespace using dot notation. of any four  1) is operator: Returns True if two variables refer to the same
package in  'x': Exclusive creation (fails if the file exists) modes 2M
Creating a package is quite straightforward, since it makes use of the program memory location.
 'a': Append (adds content to the end of the file)
operating system‟s inherent hierarchical file structure.  'b': Binary (used with other modes to handle binary files)

Page 6 / 23 Page 7 / 23 Page 8 / 23


MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)

WINTER – 2024 EXAMINATION WINTER – 2024 EXAMINATION WINTER – 2024 EXAMINATION


Model Answer – Only for the Use of RAC Assessors Model Answer – Only for the Use of RAC Assessors Model Answer – Only for the Use of RAC Assessors

Subject: Programming with Python Subject Code: 22616 Subject: Programming with Python Subject Code: 22616 Subject: Programming with Python Subject Code: 22616

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


items() Returns a list containing a tuple for each key
same memory location. o The key 2M for
dictionary value pair
 o The value
creation
Example 1: Using the "is" Operator o The items (key-value pairs) in a dictionary. syntax & pop() Removes the element with the specified key
x =[1,2,3] When we have the large amount of data, the dictionary datatype is example
y=x used. Items in dictionaries are enclosed in curly braces{ } and
popitem() Removes the last inserted key-value pair
result = x is y 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
print(result) # Output: True setdefault() Returns the value of the specified key. If the
Example: For dictionary data type.
>>> dic1={1:"First"," Second":2} key does not exist: insert the key, with the
Example 2: Using the "is not" Operator specified value
a ="hello" >>> dic1
b ="world" {1: 'First', 'Second': 2}
update() Updates the dictionary with the specified key-
>>> type(dic1)
result = a is not b value pairs
<class 'dict'>
print(result) # Output: True
>>> dic1[3]="Third"
values() Returns a list of all the values in the dictionary
>>> dic1
Assignment Operators (Augmented Assignment Operators):
{1: 'First', 'Second': 2, 3: 'Third'}
Assignment operators are used in Python programming to assign
>>> dic1.keys() c) Explain how to use user defined function in python with example. 4M
values to variables. The assignment operator is used to store the value
dict_keys([1, 'Second', 3]) Ans. • In Python, def keyword is used to declare user defined functions. Explanation
on the right-hand side of the expression on the left-hand side variable
>>> dic1.values() • The function name with parentheses (), which may or may not 2M
in the expression. Example
dict_values(['First', 2, 'Third']) include parameters and arguments and a colon:
For example, a = 5 is a simple assignment operator that assigns the 2M
>> • An indented block of statements follows the function name and
value 5 on the right to the variable a on the left.
arguments which contains the body of the function.
There are various compound operators in Python like a += 5 that adds
Python has a set of built-in methods that we can use on dictionaries. Syntax:
to the variable and later assigns the same. It is equivalent toa = a + 5.
def function_name():
Following are assignment operators in Python programming:
statements
Operator Name Example Method Description .
= Assignment Operator a = 7
.
+= Addition Assignment a += 1 # a = a + 1
clear() Removes all the elements from the dictionary Example:
-= Subtraction Assignment a -= 3 # a = a - 3
def fun():
*= Multiplication Assignment a *= 4 # a = a * 4
copy() Returns a copy of the dictionary print(“User defined function”)
/= Division Assignment a /= 3 # a = a / 3
fun()
%= Remainder Assignment a %= 10 # a = a % 10
output:
**= Exponent Assignment a **= 10 # a = a ** 10 fromkeys() Returns a dictionary with the specified keys and User defined function
value Parameterized function: The function may take arguments(s) also
b) How to create dictionary in python? Write any three methods of 4M
called parameters as input within the opening and closing
dictionary. get() Returns the value of the specified key parentheses, just after the function name followed by a colon.
Ans. Dictionary is an unordered collection of key-value pairs. It is the
Syntax:
same as the hash table type. The order of elements in a dictionary is
def function_name(argument1, argument2, ...):
undefined, but we can iterate over the following:

Page 9 / 23 Page 10 / 23 Page 11 / 23

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)

WINTER – 2024 EXAMINATION WINTER – 2024 EXAMINATION WINTER – 2024 EXAMINATION


Model Answer – Only for the Use of RAC Assessors Model Answer – Only for the Use of RAC Assessors Model Answer – Only for the Use of RAC Assessors

Subject: Programming with Python Subject Code: 22616 Subject: Programming with Python Subject Code: 22616 Subject: Programming with Python Subject Code: 22616

def disp_price(self): 4. Attempt any THREE of the following: 12M


Example: print("Price=$",self.price) a) Explain loop control statement in python. 4M
def square( x ): car1=Category() Ans. Statements used to control loops and change the course of iteration
print("Square=",x*x) are called control statements. All the objects produced within the 2M for
car1.display() listing of
# Driver code local scope of the loop are deleted when execution is completed.
square(2) car1.disp_price() Python provides the following control statements.
statements

Output: Output: 1) Break statement 2M for


Square= 4 Name= Maruti This command terminates the loop's execution and transfers the example
Price=$ 2000 program's control to the statement next to the loop.
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
Example 2: Inheritance using constructor. Example for letter in 'python programming':
inheritance if letter == 'y' or letter == 'm':
of another class. explanation class Vehicle: #parent class
break
• Inheritance provides code usability, which means that some of the def __init__(self,name):
new features can be added to the code while using the existing code. self.name=name print('Current Letter :', letter)
2M for
• The mechanism of designing or constructing classes from other example def display(self):
classes is called inheritance. print("Name= ",self.name) output : Current Letter : y
• The new class is called derived class or child class and the class class Category(Vehicle): #derived class
from which this derived class has been inherited is the base class or def __init__(self,name,price): 2) Continue statement
parent class. Vehicle.__init__(self,name) This command skips the current iteration of the loop. The statements
• In inheritance, the child class acquires the properties and can access # passing data to base class constructor following the continue statement are not executed once the Python
all the data members and functions defined in the parent class. A self.price=price interpreter reaches the continue statement.
child class can also provide its specific implementation to the Example :
def disp_price(self):
for letter in 'python program':
functions of the parent class. print("Price=$ ",self.price) if letter == 'y' or letter == 'm':
Syntax: car1=Category("Maruti",2000) continue
class A: car1.display() print('Current Letter :', letter)
# properties of class A car1.disp_price() Current Letter : p
class B(A): car2=Category("BMW",5000) Current Letter : t
# class B inheriting property of class A car2.display() Current Letter : h
# more properties of class B Current Letter : o
car2.disp_price()
Current Letter : n
Example 1: Inheritance without using constructor. Output: Current Letter : p
class Vehicle: #parent class Name= Maruti Current Letter : r
name="Maruti" Price=$ 2000 Current Letter : o
def display(self): Name= BMW Current Letter : g
print("Name= ",self.name) Price=$ 5000 Current Letter : r
class Category(Vehicle): #derived class Current Letter : a
price=2000

Page 12 / 23 Page 13 / 23 Page 14 / 23


MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)

WINTER – 2024 EXAMINATION WINTER – 2024 EXAMINATION WINTER – 2024 EXAMINATION


Model Answer – Only for the Use of RAC Assessors Model Answer – Only for the Use of RAC Assessors Model Answer – Only for the Use of RAC Assessors

Subject: Programming with Python Subject Code: 22616 Subject: Programming with Python Subject Code: 22616 Subject: Programming with Python Subject Code: 22616

try:
3) Pass statement Python does not support method overloading, that is, it is not possible ans=a/b
The pass statement is used when a statement is syntactically to define more than one method with the same name in a class in print("ANS :",ans)
necessary, but no code is to be executed. except ZeroDivisionError:
Python.
print("Division by Zero........")
Example : for letter in 'python': This is because method arguments in python do not have a type. A
pass method accepting one argument can be called with an integer value, a output :
print('Last Letter :', letter) string or a double as shown in next Enter the value of a : 10
example. Enter the value of b : 0
Last Letter : n class Demo: Division by Zero..........
b) Illustrate with example Method overloading 4M def method(self, a): d) Write the output for the following if the variable fruit : .banana 4M
Ans. It is the ability to define the method with the same name but with a Ans. >> fruit [:3] Each
2M for print(a) correct
different number of arguments and data types. With this ability one Output : ban
explanation obj= Demo() >> fruit [3:]
output 1M
method can perform different tasks, depending on the number of
obj.method(50) Output : ana
arguments or the types of the arguments given. 2M for
example obj.method('Meenakshi') >> fruit [3:3]
Method overloading is a concept in which a method in a class Output :
obj.method(100.2)
performs operations according to the parameters passed to it. As in >> fruit [:]
Output:
other languages we can write a program having two methods with Output : banana
50
same name but with different number of arguments or order of
Meenakshi e) Write a Python program to read contents from "a.txt" and write 4M
arguments but in python if we will try to do the same we will get the same contents in "b.txt". Any suitable
100.2
following issue with method overloading in Python: Ans. with open("a.txt", "r") as read_file, open("b.txt", "w") as write_file: program
Same method works for three different data types. Thus, we cannot with correct
# to calculate area of rectangle content = read_file.read()
define two methods with the same name and same number of syntax 4M
def area(length, breadth): write_file.write(content)
arguments but having different type as shown in the above example.
calc = length * breadth 5. Attempt any TWO of the following: 12M
They will be treated as the same method. It is clear that method
print calc a) Explain basic operation performed on set with suitable example. 6M
overloading is not supported in python but that does not mean that we
#to calculate area of square Ans. In Python, sets are a built-in data structure that allows you to perform 2M for each
cannot call a method with different number of arguments. There are a a variety of operations. Python provides methods and operators to operation
def area(size):
couple of alternatives available in python that make it possible to call perform the basic set operations, such as union, intersection,
calc = size * size
the same method but with different number of arguments.erample difference, symmetric difference
print calc
method overloading
area(3) 1. Union ( | or union() )
area(4,5) c) Write a Python program to check for zero division errors 4M The union of two sets combines all elements from both sets,
Output: exception. Each removing duplicates.
9 Ans. a=int(input("Enter the value of a:")) correct A = {1, 2, 3}
TypeError: area() takes exactly 1 argument (2 given) b=int(input("Enter the value of b:")) output 1M
B = {3, 4, 5}
print( A | B) # Output: {1, 2, 3, 4, 5}
print( A.union(B)) # Output: {1, 2, 3, 4, 5}

Page 15 / 23 Page 16 / 23 Page 17 / 23

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)

WINTER – 2024 EXAMINATION WINTER – 2024 EXAMINATION WINTER – 2024 EXAMINATION


Model Answer – Only for the Use of RAC Assessors Model Answer – Only for the Use of RAC Assessors Model Answer – Only for the Use of RAC Assessors

Subject: Programming with Python Subject Code: 22616 Subject: Programming with Python Subject Code: 22616 Subject: Programming with Python Subject Code: 22616

using the import statement. student.print_details()


2. Intersection ( & or intersection() ) importmy_module
The intersection of two sets returns a new set with elements common print(my_module.greet("Alice")) # Output: Hello, Alice! OUTPUT:
to both sets. print(my_module.pi) # Output: 3.14159 Enter the student's name:
A = {1, 2, 3} calc = my_module.Calculator() Alice
B = {3, 4, 5} print(calc.add(2, 3)) # Output: 5 Enter the student's roll number:101
print(A & B) # Output: {3} 3. Aliasing a Module Enterthestudent'saddress:123MainSt
print(A.intersection(B))# Output: {3} You can create an alias for a module or a function using the as Student Details:
keyword. This is often done to shorten long module names or make Name:Alice
3. Difference ( - or difference() ) code more readable. Roll No:101
The difference of two sets returns a set containing elements present in # Importing a module with an alias Address:123MainSt
the first set but not in the second. import my_module as mm 6. Attempt any TWO of the following: 12M
A = {1, 2, 3} print(mm.greet("David")) # Output: Hello, David! a) Determine various data types available in Python with example. 6M
B = {3, 4, 5} print(mm.pi) # Output: 3.14159 Ans. Python provides a variety of built-in data types, which can be
print( A– B) # Output: {1, 2} classified into several categories based on their characteristics. Here's 2M for each
c) Design a class student with data members; Name, Roll No, 6M category
a detailed description of the most common data types in Python with
print(A.difference(B))# Output: {1, 2} Address. Create suitable method for reading and printing
Defining examples:
students details.
class 2M 1. Numeric Types
b) How to write, import and alias modules. 6M Ans. class Student: Reading 2M Numeric types are used to store numbers.
Ans. In Python, modules are files containing Python code, which can 2M for def __init__(self, name, roll_no, address): Printing 2M a. Integer (int)
include functions, classes, variables, and runnable code. You can each step self.name = name An integer is a whole number without a decimal point.
write, import, and alias modules to organize and reuse your code self.roll_no = roll_no x = 10 # Integer
efficiently. self.address = address y = -25 # Negative integer
1. Writing a Python Module defread_details(self): print(x, type(x))
self.name = input("Enter the student's name: ") # Output: 10 <class 'int'>
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: self.roll_no = input("Enter the student's roll number: ")
b. Floating-Point (float)
def greet(name): self.address = input("Enter the student's address: ") A float is a number that has a decimal point or is in exponential form.
return f"Hello, {name}!" x = 3.14 # Float
pi = 3.14159 defprint_details(self): y = -2.71 # Negative float
class Calculator: print("Student Details:") print(x, type(x))
def add(self, a, b): print(f"Name: {self.name}") # Output: 3.14 <class 'float'>
return a + b print(f"Roll No: {self.roll_no}")
def multiply(self, a, b): print(f"Address: {self.address}")
c. Complex Number (complex)
return a * b A complex number has a real part and an imaginary part, represented
2. Importing a Module in Python student = Student("", "", "") as a + bj, where a and b are real numbers and j is the imaginary unit.
Once you have a module, you can import it into another Python file student.read_details() x = 2 + 3j# Complex number

Page 18 / 23 Page 19 / 23 Page 20 / 23


MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)

WINTER – 2024 EXAMINATION WINTER – 2024 EXAMINATION WINTER – 2024 EXAMINATION


Model Answer – Only for the Use of RAC Assessors Model Answer – Only for the Use of RAC Assessors Model Answer – Only for the Use of RAC Assessors

Subject: Programming with Python Subject Code: 22616 Subject: Programming with Python Subject Code: 22616 Subject: Programming with Python Subject Code: 22616

print(x, type(x)) # Output: (2+3j) <class 'complex'> b) Write a Python program to read contents of first.txt file and 6M # Code that runs if no exception was raised
write same content in second.txt file. finally:
2. Sequence Types Ans. # Open the first.txt file in read mode with open('first.txt', 'r') as file1: Reading # Code that always runs (cleanup code)
Sequence types store an ordered collection of items. # Read the content of the first file contents of
first file 3M
content = file1.read() Explanation of Components
a. String (str) # Open the second.txt file in write mode (it will create the file if it try Block: Contains the code that might raise an exception.
A string is a sequence of characters enclosed within single (') or doesn't exist) except Block: Catches and handles the exception.
double (") quotes. with open('second.txt', 'w') as file2: Writing else Block: Executes if the try block succeeds without any exceptions.
# Write the content to the second file contents of finally Block: Executes regardless of whether an exception was raised
name = "John" # String
first file to
message = 'Hello, World!' file2.write(content) second file
or not. Typically used for cleanup tasks.
print(name, type(name)) # Output: John <class 'str'> print("Contents of first.txt have been copied to second.txt.") 3M
Example:
. List (list)
Explanation:
A list is an ordered, mutable collection that can contain elements of Opening first.txt: try:
any data type, including other lists. The open() function is used with the 'r' mode to open first.txt in read # Try to open and read a file
fruits = ['apple', 'banana', 'cherry'] # List mode. file = open("example.txt", "r")
print(fruits, type(fruits)) # Output: ['apple', 'banana', 'cherry'] <class with open() is used to ensure the file is properly closed after the content = file.read()
'list'> operation is complete. print(content)
Reading the contents: except FileNotFoundError:
file1.read() reads the entire content of first.txt into the variable # Handle the specific exception if the file doesn't exist
3. Mapping Type content. print("Error: The file was not found.")
Mapping types store key-value pairs. Opening second.txt: except IOError:
a. Dictionary (dict) The open() function is used with the 'w' mode to open second.txt in # Handle other I/O errors
A dictionary is an unordered, mutable collection of key-value pairs, write mode. print("Error: An IOError occurred.")
where each key is unique. If second.txt does not exist, it will be created automatically. else:
person = {'name': 'Alice', 'age': 25, 'city': 'New York'} Writing the contents: # Executes if no exceptions were raised
file2.write(content) writes the content read from first.txt into print("File was read successfully!")
print(person, type(person)) # Output: {'name': 'Alice', 'age': 25, 'city':
second.txt. finally:
'New York'} <class 'dict'> c) Explain Try-except-else-finally block used in exception handling 6M # Always executes, used to clean up resources
in Python with example. try:
4. Set Types Ans. The try-except-else-finally block is a comprehensive way to handle Each file.close()
Set types are used to store unordered collections of unique elements. exceptions in Python. It allows you to test a block of code for errors explanatio print("File has been closed.")
(try), handle the errors if they occur (except), execute code if no n ,syntax except NameError:
a. Set (set)
errors occur (else), and execute cleanup code regardless of whether an and print("File object does not exist.")
A set is an unordered collection of unique elements, and it is mutable example
(you can add or remove items). error occurred or not (finally).
2M
fruits = {'apple', 'banana', 'cherry'} # Set
print(fruits, type(fruits)) # Output: {'banana', 'apple', 'cherry'} <class try:
'set'> # Code that might raise an exceptionexcept ExceptionType:
# Code to handle the exception
else:

Page 21 / 23 Page 22 / 23 Page 23 / 23

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
_________ _________ _________
SUMMER – 2024 EXAMINATION reverse (Optional): for reverse=True, it will sort the list descending. Default is 2. Attempt any THREE of the following: 12 M
Model Answer – Only for the Use of RAC Assessors reverse=False
key (Optional): A function to specify the sorting criteria. a) Explain with example: 4M
Subject Name: Programming with Python Subject Code:
22616 d) Write use of matplotlib package in python. 2M i) Indentation
Important Instructions to examiners:
ii) Variables
1) The answers should be examined by key words and not as word-to-word as given in the model answer scheme. Ans Use of matplotlib package in python: 1M
2) The model answer and the answer written by candidate may vary but the examiner may try to assess the 1) Matplotlib is use for creating static, animated, and interactive visualizations in Ans i) Indentation: For each
understanding level of the candidate. Python. (for each • Python provides no braces to indicate blocks of code for class and function correct
3) The language errors such as grammatical, spelling errors should not be given more Importance (Not applicable for 2) It is used along with NumPy to provide an environment that is an effective open- use of definitions or flow control. explanation
subject English and Communication Skills. matplotlib
source alternative for MATLAB. • Blocks of code are denoted by line indentation, which is compulsory. and
4) While assessing figures, examiner may give credit for principal components indicated in the figure. The figures drawn package) Example – 2
by candidate and model answer may vary. The examiner may give credit for any equivalent figure drawn.
3) Matplotlib can be used in Python scripts, the Python and IPython shell, web • The number of spaces in the indentation is variable, but all statements within
application servers, and various graphical user interface toolkits like Tkinter, the block must be indented the same amount. M
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. awxPython, etc.
6) In case of some questions credit may be given by judgement on part of examiner of relevant answer based on
e) What is data abstruction and data hiding. 2M
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 + Ans Data abstraction: Data Abstraction is used to hide the internal functionality of the 1M
Marathi) medium is introduced at first year of AICTE diploma Programme from academic year 2021-2022. Hence if function from the users. The users only interact with the basic implementation of the
the students in first year (first and second semesters) write answers in Marathi or bilingual language (English function, but inner working is hidden. User is familiar with that "what function (for
+Marathi), the Examiner shall consider the same and assess the answer based on matching of concepts with model does" but they don't know "how it does." definition of
answer. data
Data hiding: Data hiding is a concept which underlines the hiding of data or information abstraction Figure of Indentation
Q. Sub Answer Marking from the user. Data hiding is a software development technique specifically used in and data • Example:
No. Q. Scheme Object-Oriented Programming (OOP) to hide internal object details (data members). hiding)
if True:
N. Data hiding includes a process of combining the data and functions into a single unit to print "True"
conceal data within a class by restricting direct access to the data from outside the class. else:
1 Attempt any FIVE of the following: 10 M print "False"
a) Enlist any four data structures used in python. 2M
f) Write the syntax of fopen. 2M • Thus, in Python all the continuous lines indented with same number of spaces
would form a block.
Ans Syntax of fopen: 2 M for ii) Variables:
Ans Data structures used in python are: 2M
1) List (Any 4
f=open(filename, mode) correct • Python Variable is containers that store values.
2) Set correct data
Were, syntax • We do not need to declare variables before using them or declare their type.
3) Tuple structures
filename: This parameter as the name suggests, is the name of the file that we want to • A variable is created the moment we first assign a value to it.
open. • A Python variable is a name given to a memory location.
4) Dictionary name)
5) Frozen Sets mode: This parameter is a string that is used to specify the mode in which the file is to be • It is the basic unit of storage in a program.
b) Give membership operators in python. 2M opened. • Variable Naming Rules in Python
1) Variable name should start with letter(a-z ,A-Z) or underscore (_).
Ans Membership operators are: 1M g) What is dictionary? 2M
Example: age, _age, Age
In: Give result true if value is found in list or in sequence, and give result false if item is 2) In variable name, no special characters allowed other than underscore (_).
not in list or in sequence (for each Ans Dictionary is an unordered collection of key-value pairs. 2 M for
Membership Example: age_, _age
Not in: Give result true if value is not found in list or in sequence, and give result false if OR correct 3) Variables are case sensitive.
item is in list or in sequence. Operators) In Python, dictionaries are mutable data structures that allow you to store key-value pairs. explanation Example: age and Age are different, since variable names are case
Dictionary can be created using the dict() constructor or curly braces' {}'. of sensitive.
c) Write syntax for a method to sort a list. 2M
dictionary 4) Variable name can have numbers but not at the beginning.
Ans Syntax of sort method for a list: 2 M for Example: Age1
list.sort(reverse=True|False, key=myFunc) correct 5) Variable name should not be a Python reserved keyword.
Were, syntax • Example:

Page No: 1 | 19 Page No: 2 | 19 Page No: 3 | 19


MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
_________ _________ _________
x = 5 # x is of type integer • NumPy is the fundamental package for scientific computing with Python. correct 3. Attempt any THREE of the following: 12 M
y = "John" # y is of type string NumPy stands for "Numerical Python". It provides a high-performance explanation)
b) Print the following pattern using loop: 4M a) What is the output of the following program? 4M
multidimensional array object, and tools for working with these arrays.
1010101 • An array is a table of elements (usually numbers), all of the same type, dict1={'Google': 1, 'Facebook': 2, 'Microsoft': 3}
indexed by a tuple of positive integers and represented by a single variable.
10101 dict2={'GFG': 1, 'Microsoft': 2, 'Youtube': 3}
NumPy's array class is called ndarray. It is also known by the alias array.
101 • In NumPy arrays, the individual data items are called elements. All elements dict1.update(dict2);
1 of an array should be of the same type. Arrays can be made up of any
number of dimensions. for key, values in dictl-items():
Ans p = '1' 4M • In NumPy, dimensions are called axes. Each dimension of an array has a
q = '0' (for any print (key, values)
length which is the total number of elements in that direction.
j=0 correct
k=4 program • The size of an array is the total number of elements contained in an array in Ans Google 1 4 M for
all the dimension. The size of NumPy arrays are fixed; once created it cannot correct
while k >= 1: with proper Facebook 2
be changed again. output
print(" "*j + (k-1)*(p+q) +p+ " "*j) logic)
k = k-1 • Numpy arrays are great alternatives to Python Lists. Some of the key Microsoft 2
j=j+1 advantages of Numpy arrays are that they are fast, easy to work with, and
c) Write python program to perform following operations on set. 4M GFG 1
give users the opportunity to perform calculations across entire arrays.
Youtube 3
i) Create set of five elements.
b) Write a python program that takes a number and checks whether it is a 4M
ii) Access set elements.
palindrome.
iii) Update set by adding one element.
Ans def is_palindrome(num): 2 M for
iv) Remove one element from set. logic,
original_num = num
2 M for
Ans i) Create set of five elements 1M reverse_num = 0 correct
set1 = {11, 22, 33,44,55} (each for
program
ii) Access set elements correct Figure shows the axes (or dimensions) and lengths of two example arrays; while num > 0:
print("\nElements of set: ") operations (a) is a one-dimensional array and (b) is a two-dimensional array.
for i in set1: on set ) digit = num % 10
print(i) ii) Panda reverse_num = (reverse_num * 10) + digit
iii) Update set by adding one element • Pandas is a powerful and versatile library that simplifies the tasks of data
set1.add(88) num //= 10
manipulation in Python.
iv) Remove one element from set.
set1.discard(44) • Pandas is well-suited for working with tabular data, such as spreadsheets or return original_num == reverse_num
Or SQL tables.
number = 12321
set1.remove(44) • The Pandas library is an essential tool for data analysts, scientists, and
d) Describe following Standard Packages 4M engineers working with structured data in Python. if is_palindrome(number):
• It is built on top of the NumPy library which means that a lot of the
i) Numpy print(f"{number} is a palindrome.")
structures of NumPy are used or replicated in Pandas.
ii) Pandas • The data produced by Pandas is often used as input for plotting functions in else:
Matplotlib, statistical analysis in SciPy, and machine learning algorithms in
Ans i) Numpy 2M print(f"{number} is not a palindrome.")
Scikit-learn.
(for each

Page No: 4 | 19 Page No: 5 | 19 Page No: 6 | 19

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
_________ _________ _________
Output: 12321 is a palindrome. • A tuple data type in python programming is similar to a list data type, which also The implication of iterations is The implication of iterations is correct
2
contains heterogeneous items/elements. Time-consuming comparatively Faster points.
c) Write a python program to create a user defined module that will ask your 4M
program name and display the name of the program. Example: For tuple. The list is better for performing
A Tuple data type is appropriate for
3 operations, such as insertion and
a=(10,'abc',1+3j) accessing the elements
Ans User Defined Module- ProgramName.py 4 M for deletion.
correct
def pName(str): print(a) Tuple consumes less memory as
program. 4 Lists consume more memory
(10, 'abc', (1+3j)) compared to the list
print("Name of program is : ",str)
Example 2:List Data Type Tuple does not have many built-in
5 Lists have several built-in methods
methods.
Main program- Program.py List is an ordered sequence of items. It is one of the most used datatype in Python and is
very flexible. Unexpected changes and errors are Because tuples don’t change they are
6
import ProgramName more likely to occur far less error-prone.
• List can contain heterogeneous values such as integers, floats, strings, tuples, lists and
str=input("Enter program name: ") dictionaries but they are commonly used to store collections of homogeneous objects. Syntax: Enclosed in Square ([])
7 Syntax: Enclosed in Square (()) bracket
bracket
ProgramName.pName(str) • The list datatype in Python programming is just like an array that can store a group of
elements and we can refer to these elements using a single name. Example: Example:
Output- 8
• Declaring a list is pretty straight forward. Items separated by commas ( , ) are enclosed Employee = [‘A’, ‘B’, ‘C’] Employee = (1001, 1002, 1003)
Enter program name: Program within brackets [ ].
b) Write a python program takes in a number and find the sum of digits in a 4M
Name of program is : Program Example: number.
d) List data types used in python. Explain any two with example. 4M For list. Ans Number = int(input("Please Enter any Number: ")) 4 M for
correct
Ans Python has various standard data types that are used to define the operations possible on 2 M for first=[10, 20, 30] Sum = 0 program.
them and the storage method for each of them. Data types in Python programming types,
includes: # homogenous values in list while(Number > 0):
2 M for two
1. Numbers: Represents numeric data to perform mathematical operations. second=["One","Two","Three"] Reminder = Number % 10
proper
2. String: Represents text characters, special symbols or alphanumeric data. examples Print(first) Sum = Sum + Reminder

3. List: Represents sequential data that the programmer wishes to sort, merge etc. [10, 20, 30] Number = Number //10

4. Tuple: Represents sequential data with a little difference from list. Print(second) print("\n Sum of the digits of Given Number = %d" %Sum)

5. Dictionary: Represents a collection of data that associate a unique key with each value. ['One', 'Two', 'Three'] Output:

6. Boolean: Represents truth values (true or false). Please Enter any Number: 12

Example1: Tuple Data Type 4. Attempt any THREE of the following: 12 M Sum of the digits of Given Number = 3

• Tuple is an ordered sequence of items same as list. The only difference is that tuples are a) Compare list and tuple (any four points). 4M c) Write a program function that accepts a string and calculate the number of 4M
immutable. Tuples once created cannot be modified. uppercase letters and lower case letters.
Ans Sno. LIST TUPLE 1 M each
• Tuples are used to write-protect data and are usually faster than list as it cannot change for one Ans Str=input("Enter a String -: ") 4 M for
dynamically. It is defined within parentheses ( ) where items are separated by commas ( , 1 Lists are mutable Tuples are immutable point. def upperlower(Str): correct
). 4 M for 4 lower=0 program.
upper=0
for i in Str:
Page No: 7 | 19 Page No: 8 | 19 Page No: 9 | 19
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
_________ _________ _________
if(i.islower()): Example:
lower+=1
elif(i.isupper()): def set_data(self, rollno): Open a file and print the content:
upper+=1 self.rollno = rollno
print("The number of lowercase characters is:",lower) f = open("demofile.txt", "r")
print("The number of uppercase characters is:",upper) print(f.read())

def display_data(self):
upperlower(Str)
print(f"Roll No: {self.rollno}") ii) The write() function
student1 = Student(10)
Output - The write() method writes a specified text to the file.
Enter a String -: Welcome to Python programing student1.display_data()
The number of lowercase characters is: 23 Where the specified text will be inserted depends on the file mode and stream position.
The number of uppercase characters is: 2
"a": The text will be inserted at the current file stream position, default at the end of the
Output: file.
or
Rollno = 10
"w": The file will be emptied before the text will be inserted at the current file stream
string = input("Enter a String -: ") e) Explain following functions with example: 4M position, default 0.
def upperlower(string):
upper = 0 i) The open() function Syntax:
lower = 0
ii) The write() function file.write(byte)
for i in range(len(string)):
# For lower letters byte: The text or byte object that will be inserted.
Ans i) The open() function 2 M each
if (ord(string[i]) >= 97 and ord(string[i]) <= 122): #ord() function is used to convert
for one
a single Unicode character into its integer representation The open() function opens a file and returns it as a file object. Example:
point and
lower += 1 Open the file with "a" for appending, then add some text to the file:
Syntax: proper
# For upper letters
explanation f = open("demofile2.txt", "a")
elif (ord(string[i]) >= 65 and ord(string[i]) <= 90):
open(file, mode) with f.write("Hi!")
upper += 1
example. f.close()
file: The path and name of the file
print('Lower case characters = %s' %lower, '\nUpper case characters = %s' %upper)
mode: A string, define which mode you want to open the file in: #open and read the file after the appending:
upperlower(string) f = open("demofile2.txt", "r")
"r" - Read - Default value. Opens a file for reading, error if the file does not exist print(f.read())
Output-
"a" - Append - Opens a file for appending, creates the file if it does not exist
Enter a String -: Welcome to Python programming
Lower case characters = 24 "w" - Write - Opens a file for writing, creates the file if it does not exist 5. Attempt any TWO of the following: 12 M
Upper case characters = 2
"x" - Create - Creates the specified file, returns an error if the file exist a) Write the output for the following if the variable course = "Python" 6M
d) Write a python program to create class student with roll-no. and display its 4M
contents. In addition you can specify if the file should be handled as binary or text mode >>> course [ : 3 ]

Ans class Student: 4 M for "t" - Text - Default value. Text mode >>> course [ 3 : ]
correct "b" - Binary - Binary mode (e.g. images)
def init (self, rollno): program. >>> course [ 2 : 2 ]
self.rollno = rollno >>> course [:]

Page No: 10 | 19 Page No: 11 | 19 Page No: 12 | 19

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
_________ _________ _________
>>> course [-1] CO diploma" and "I am with IF diploma' respectively. Call the method by Ans Multiple inheritance is a feature in object-oriented programming where a class can 2 M-
creating an object of each of the three classes. inherit attributes and methods from more than one parent class. This allows a class to Explanation,
>>> course [1] 4 M-any
combine and reuse code from multiple classes, promoting code reuse and modular
Ans class Diploma: 6 M - Any suitable
Ans >>>course[:3] 1 M for design.
correct logic example
each one def getdiploma(self): program
Ans: Pyt question In Python, you can achieve multiple inheritance by specifying multiple parent classes in
print("I got diploma") the definition of a child class.
course[3:]
Program:
Ans: hon
class CO(Diploma): class Person:
>>>course[2:2]
def getdiploma(self): def init (self, name, age):
Ans: a slice starting and ending at the same index, which results in an empty string. Slicing
in this way doesn't include any characters between the specified indices. print("I am with CO diploma") self.name = name

>>>course[:] self.age = age

Ans: Python class IF(Diploma):

>>>course[-1] def getdiploma(self): def display_person(self):

Ans: n print("I am with IF diploma") print(f"Name: {self.name}, Age: {self.age}")

>>> course[1]

Ans: y # Create objects of each class class Employee:

b) Write a python program to generate five random integers between 10 and 50 6M diploma_obj = Diploma() def init (self, employee_id, position):
using numpy library.
co_obj = CO() self.employee_id = employee_id
Ans import numpy as np 6 M- Any
if_obj = IF() self.position = position
correct logic
random_integer = np.random.randint(10, 51) program

print(f"Random integer between 10 and 50: {random_integer}")


# Call the getdiploma method on each object def display_employee(self):
# If you want to generate an array of random integers, you can specify the size
diploma_obj.getdiploma() # Output: I got diploma print(f"Employee ID: {self.employee_id}, Position: {self.position}")
# For example, to generate 5 random integers between 10 and 50:
co_obj.getdiploma() # Output: I am with CO diploma
random_integers_array = np.random.randint(10, 51, size=5)
if_obj.getdiploma() # Output: I am with IF diploma class Manager(Person, Employee):
print(f"Array of random integers between 10 and 50: {random_integers_array}")
def init (self, name, age, employee_id, position, department):
c) Write a Python program to create a class 'Diploma' having a method 6M
6. Attempt any TWO of the following: 12 M Person. init (self, name, age)
‘getdiploma’ that prints "I got a diploma". It has two subclasses namely 'CO'
and 'IF' each oſ having a method with the same name that prints "I am with a) Explain multiple inheritance and write a python program to implement it. 6M Employee. init (self, employee_id, position)

Page No: 13 | 19 Page No: 14 | 19 Page No: 15 | 19


MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
_________ _________ _________
self.department = department print("Password is correct. Access granted.") • This is the default mode for text files (although you don't explicitly specify
it). It's used to handle text files and performs encoding/decoding of text
automatically.
def display_manager(self): # Main program to check the password • Example: open('file.txt', 'rt')

self.display_person() try: 6. Read and Write Mode ('r+'):


• Opens the file for both reading and writing.
self.display_employee() user_password = input("Enter your password: ")
• The file pointer is at the beginning of the file.
print(f"Department: {self.department}") check_password(user_password)
• Example: open('file.txt', 'r+')
except InvalidPasswordException as e:
7. Write and Read Mode ('w+'):
# Create an instance of Manager print(e)
• Opens the file for both reading and writing.
manager = Manager("Alice", 35, "M123", "Project Manager", "IT") c) Describe various modes of file object. Explain any three in detail. 6M • If the file doesn't exist, it creates a new file.
Ans 1. Read Mode ('r'): Any 3 • If the file exists, it truncates the file to zero length.
modes, each
# Display manager details • This is the default mode. It opens the file for reading. mode for 2 • Example: open('file.txt', 'w+')
• If the file doesn't exist, it raises a FileNotFoundError. M
manager.display_manager() Detailed Explanation of Three Modes:
• When opened in this mode, attempting to write to the file will raise a
b) Write a Python program to create user defined exception that will check 6M 1. Read Mode ('r'):
UnsupportedOperation error.
whether the password is correct or not. • This mode is primarily used when you want to read data from an existing
• Example: open('file.txt', 'r') file.
Ans class InvalidPasswordException(Exception): 6 M - Any
correct logic 2. Write Mode ('w'): • It's useful for operations like reading configuration files, log files, or any
"""Exception raised for invalid passwords.""" program other file where you need to retrieve information.
• Opens the file for writing. If the file doesn't exist, it creates a new file.
def init (self, message="Password is incorrect"): • If the file already exists, it truncates the file to zero length. • Reading from a file opened in read mode does not modify the file.

self.message = message • Example: open('file.txt', 'w') • Attempting to write to a file opened in read mode will raise an error.

super(). init (self.message) 3. Append Mode ('a'): 2. Write Mode ('w'):

• Opens the file for writing. If the file doesn't exist, it creates a new file. • This mode is used when you want to write data to a file.

• If the file already exists, it appends data to the end of the file. • If the file already exists, opening it in write mode will truncate the file to
def check_password(input_password): zero length, effectively deleting its contents.
• Example: open('file.txt', 'a')
correct_password = "SecurePassword123" # Replace with the actual correct password • If the file doesn't exist, Python will create a new file.
4. Binary Mode ('b'):
• It's commonly used for tasks like writing output to a file, logging data, or
• Opens the file in binary mode. It's used in conjunction with other modes creating new files.
if input_password != correct_password: like read ('rb'), write ('wb'), or append ('ab') to deal with binary files like
images, executables, etc. 3. Append Mode ('a'):
raise InvalidPasswordException("The password you entered is incorrect.")
• Example: open('image.jpg', 'rb') • Append mode is similar to write mode but instead of truncating the file, it
else: appends data to the end of the file.
5. Text Mode ('t'):
• If the file doesn't exist, it creates a new file.

Page No: 16 | 19 Page No: 17 | 19 Page No: 18 | 19

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
_________
• It's useful when you want to add data to an existing file without overwriting
its contents.
• Common use cases include logging, adding new entries to a file, or
maintaining a history of operations.

Page No: 19 | 19

You might also like