0% found this document useful (0 votes)
8 views45 pages

All Python Model Answer Paper

The document is a model answer scheme for the Winter 2023 examination of the Programming with Python subject by the Maharashtra State Board of Technical Education. It provides guidelines for examiners on assessing student answers, including the importance of understanding over exact wording, and offers a variety of questions with model answers related to Python programming concepts. Key topics include the use of keywords, data hiding, namespaces, and built-in list functions.

Uploaded by

Mini TV
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)
8 views45 pages

All Python Model Answer Paper

The document is a model answer scheme for the Winter 2023 examination of the Programming with Python subject by the Maharashtra State Board of Technical Education. It provides guidelines for examiners on assessing student answers, including the importance of understanding over exact wording, and offers a variety of questions with model answers related to Python programming concepts. Key topics include the use of keywords, data hiding, namespaces, and built-in list functions.

Uploaded by

Mini TV
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/ 45

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

(Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________
WINTER – 2023 EXAMINATION  Software Development
Model Answer – Only for the Use of RAC Assessors  Web Applications
b) Write the use of elif keyword in python. 2M
Subject Name: Programming with Python Subject Code: 22616 22616
Important Instructions to examiners: Ans elif' stands for 'else if' and is used in Python programming to test multiple conditions. Correct
1) The answers should be examined by key words and not as word-to-word as given in the model answer scheme. The if statements are executed from the top down. As soon as one of the conditions controlling explanation 2
2) The model answer and the answer written by candidate may vary but the examiner may try to assess the understanding the if is true, the statement associated with that if is executed, and the rest of the ladder is M
level of the candidate. bypassed. If none of the conditions is true, then the final else statement will be executed.
3) The language errors such as grammatical, spelling errors should not be given more Importance (Not applicable for
subject English and Communication Skills.
4) While assessing figures, examiner may give credit for principal components indicated in the figure. The figures drawn c) Describe the Role of indentation in python. 2M
by candidate and model answer may vary. The examiner may give credit for any equivalent figure drawn.
5) Credits may be given step wise for numerical problems. In some cases, the assumed constant values may vary and Ans  Indentation refers to the spaces at the beginning of a code line. Correct Role 2
there may be some difference in the candidate’s answers and model answer.  Generally, four whitespaces are used for indentation and is preferred over tabs. M
6) In case of some questions credit may be given by judgement on part of examiner of relevant answer based on  Where in other programming languages the indentation in code is for readability only,
candidate’s understanding. the indentation in Python is very important.
7) For programming language papers, credit may be given to any other program based on equivalent concept.  Indentation helps to convey a better structure of a program to the readers. It is used to
8) As per the policy decision of Maharashtra State Government, teaching in English/Marathi and Bilingual (English + clarify the link between control flow constructs such as conditions or loops, and code
Marathi) medium is introduced at first year of AICTE diploma Programme from academic year 2021-2022. Hence if contained within and outside of them.
the students in first year (first and second semesters) write answers in Marathi or bilingual language (English  Python uses indentation to indicate a block of code.
+Marathi), the Examiner shall consider the same and assess the answer based on matching of concepts with model Example:
answer. if 5 > 2:
print("Five is greater than two!")
Q. Sub Answer Marking d) Define Data Hiding concept? Write two advantages of Data Hiding. 2M
No. Q. Scheme
N. Ans  Data hiding is a concept which underlines the hiding of data or information from the Any relevant
user. Definition 1 M,
1 Attempt any FIVE of the following: 10 M  Data hiding is a software development technique specifically used in Object-Oriented
any two
Enlist applications for python programming. Programming (OOP) to hide internal object details (data members).
a) 2M Advantages 1
 Data hiding includes a process of combining the data and functions into a single unit
Ans  Google's App Engine web development framework uses Python as an application Any two to conceal data within a class by restricting direct access to the data from outside the M
language. application, class.
 Maya, a powerful integrated 3D modeling and animation system, provides a Python One application
scripting API. Advantages of Data Hiding
for 1 M each
 Linux Weekly News, published by using a web application written in Python.  Data hiding ensures exclusive data access to class members and protects object
 Google makes extensive use of Python in its Web Search Systems. integrity by preventing unintended or intended changes.
 The popular YouTube video sharing service is largely written in Python  Data hiding is also known as information hiding. An object's attributes may or may
programming. not be visible outside the class definition.
 The NSA uses Python for cryptography and intelligence analysis.  Data hiding also minimizes system complexity for increase robustness by limiting
interdependencies between software requirements.
 iRobot uses Python programming to develop commercial and military robotic devices.
 The objects within the class are disconnected from irrelevant data.
 The Raspberry Pi single-board computer promotes Python programming as its
educational language.  It heightens the security against hackers that are unable to access confidential data.
 Nextflix and Yelp have both documented the role of Python in their software  It helps to prevent damage to volatile data by hiding it from the public.
infrastructures.  A user outside from the organization cannot attain the access to the data.
 Industrial Light and Magic, Pixar and others uses Python in the production of  Within the organization/ system only specific users get the access. This allows better
animated movies. operation.
 Desktop GUI Applications e) State use of namespace in python. 2M
 Image Processing Applications
 Scientific and Numeric Applications Ans  Namespaces bring you three advantages: they group names into logical Correct/relevant
 Audio and Video Based Applications containers, they prevent clashes between duplicate names, and third, they use 2 M
 3D CAD Applications provide context to names.
Page No: 1 | 20 Page No: 2 | 20
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________
 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
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.
 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
namespace in the form of a Python dictionary. [10,20]
 A namespace in python is a collection of names. So, a namespace is essentially >>> list1.insert(1,30)
a mapping of names to corresponding objects. >>> list1
f) State the use of read() and readline () functions in python file handling. 2M [10, 30, 20]

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
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
three characters of the file.
Example: for read( ) method. Ans Membership Operators: Membership
(example is not
f=open("sample.txt","r") The membership operators in Python are used to find the existence of a particular operator 2 M
mandatory)
print(f.read(5)) # read first 5 data element in the sequence, and used only with sequences like string, tuple, list, and Identity
print(f.read()) # read rest of the file dictionary etc.
operator 2 M
Membership operators are used to check an item or an element that is part of a string,
2. readline([n]) Method: a list or a tuple. A membership operator reduces the effort of searching an element in
The readline() method just output the entire line whereas readline(n) outputs at most the list.
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
file is reached, we get empty string on further reading. and used to test whether a value or variable is in a sequence.
Example: For readline ( ) method. Operator Description Example
f=open("sample.txt","r")
print(f.readline()) # read first line followed by\n in True if value is found in list or in >>> x="Hello World"
print(f.readline(3)) sequence, and false it item is not >>> print('H' in x)
print(f.readline()) in list or in sequence True
g) Explain two ways to add objects / elements to list. 2M not in True if value is not found in list >>> x="Hello World"
or in sequence, and false it item is >>> print("Hello" not in x)
1)append method: The append() method adds an element to the end of a list. We can insert in list or in sequence. False
Ans 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
>>> list1=[10,20,30] methods) memory address of two objects; this is made possible with the help of the identity
>>> list1 operator. Identity operators are used to check whether both operands are same or not.
[10, 20, 30] Python provides ‘is’ and ‘is not’ operators which are called identity operators and both
>>> list1.append(40) # add element at the end of list are used to check if two values are located on the same part of the memory. Two
>>> list1 (example is not
variables that are equal does not imply that they are identical.
[10, 20, 30, 40] mandatory) Operator Description Example

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
several items using extend() method. and false otherwise. >>> print(a is b)
Example: Program for extend() method. True
>>>list1=[10, 20, 30, 40] is not Return false, if the variables on either >>> a=3
>>>list1 side of the operator point to the same >>> b=3
[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
>>> list1
[10, 20, 30, 40, 60, 70] b) Write python program to display output like. 4M

Page No: 3 | 20 Page No: 4 | 20


MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________
2 >>> list1.pop(2)
4 6 8 7
10 12 14 16 18 10 list.remove(item) It deletes the given item >>> list1
Ans a=2 Correct or any from the list. [1, 2, 3, 4, 5]
for i in range(1,5): relevant Logic/ >>> list1.remove(3)
for j in range(i): any other >>> list1
print(a,end="\t") suitable [1, 2, 4, 5]
a+=2 11 list.reverse() It reverses the position >>> list1
Program 4 M
print() (index number) of the items [1, 2, 3, 4, 5]
in the list. >>> list1.reverse()
c) Explain four built-in list functions. 4M >>> list1
[5, 4, 3, 2, 1]
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]
Any 4 functions function if provided. >>> list1.sort()
list. [1, 2, 3, 4, 5]
>>> len(list1) 4 M, 1 M each >>> list1
5 [1, 2, 3, 4, 5]
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
the maximum value in a [1, 2, 3, 4, 5] importing it.
list. >>> max(list1)
5 Ans For creating a module write following code and save it as p1.py Write module 2
3 sum(list) Calculates sum of all the >>>list1 #p1.py M and Import 2
elements of list. [1, 2, 3, 4, 5] def add(a, b): M
>>>sum(list1) "This function adds two numbers and return the result"
15 result = a + b
4 min(list) It returns the item that has >>> list1 return result
the minimum value in a list. [1, 2, 3, 4, 5]
>>> min(list1)
def sub(a, b):
1
"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
>>> list(list1) return result
[1, 2, 3, 4, 5]
6 list.append(item) It adds the item to the end >>> list1 Import the definitions inside a module:
of the list. [1, 2, 3, 4, 5]
>>> list1.append(6) import p1
>>> list1 print(p1.add(10,20))
[1, 2, 3, 4, 5, 6] print(p1.sub(20,10))
7 list.count(item) It returns number of times >>> list1
the item occurs in the list. [1, 2, 3, 4, 5, 6, 3]
>>> list1.count(3)
Output:
2 30
8 list.extend(seq) It adds the elements of the >>> list1 10
sequence at the end of the [1, 2, 3, 4, 5]
list. >>> list2
['A', 'B', 'C']
>>> list1.extend(list2) 3. Attempt any THREE of the following: 12 M
>>> list1
[1, 2, 3, 4, 5, 'A', 'B', 'C'] a) Describe various modes of file object? Explain any two in detail. 4M
9 list.pop(item=list[- It deletes and returns the >>> list1
1]) last element of the list. [1, 2, 7, 3, 4, 5, 3]
>>> list1.pop()
3
Page No: 5 | 20 Page No: 6 | 20
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________
Ans Like, C, C++, and Java, a file in Python programming can be opened in various modes Listing of That is, the file is in the append mode. If the file does
depending upon the purpose. For that, the programmer needs to specify the mode modes- 1 M not exist, it creates a new file for writing.
whether read 'r', write 'w', or append 'a' mode. Apart from this, two other modes exist, and explain ant
which specify to open the file in text mode or binary mode. 2- 3 M 10 ab Opens a file for appending in binary format. The file
1. The text mode returns strings while reading from the file. The default is reading in pointer is at the end of the file if the file exists. That is,
text mode. the file is in the append mode. If the file does not exist,
2. The binary mode returns bytes and this is the mode to be used when dealing with
it creates a new file for writing.
non-text files like image or executable files.
The text and binary modes are used in conjunction with the r, w, and a modes. The list
11 a+ Opens a file for both appending and reading. The file
of all the modes used in Python are given in following table:
pointer is at the end of the file if the file exists. The file
Sr. No. Mode Description
opens in the append mode. If the file does not exist, it
1 r Opens a file for reading only. The file pointer is placed creates a new file for reading and writing.
at the beginning of the file. This is the default mode.
12 ab+ Opens a file for both appending and reading in binary
2 rb Opens a file for reading only in binary format. The file format. The file pointer is at the end of the file if the
pointer is placed at the beginning of the file. This is the file exists. The file opens in the append mode. If the file
default mode. does not exist, it creates a new file for reading and
writing.
3 r+ Opens a file for both reading and writing. The file
pointer placed at the beginning of the file. 13 t Opens in text mode (default).

4 rb+ Opens a file for both reading and writing in binary 14 b Opens in binary mode
format. The file pointer placed at the beginning of the
15 + Opens a file for updating (reading and writing).
file.

5 w Opens a file for writing only. Overwrites the file if the


file exists. If the file does not exist, creates a new file
b) Explain use of Pass and Else keyword with for loops in python. 4M
for writing.
Ans Pass Statement: It is used when a statement is required syntactically but we do not Pass for 2 M
6 wb Opens a file for writing only in binary format. want any command or code to execute. A pass statement in Python also refers to as a and Else for 2
Overwrites the file if the file exists. If the file does not will statement. The pass statement is a null operation; nothing happens when it executes. M
exist, creates a new file for writing. The pass is also useful in places where your code will eventually go, but has not been written
yet.
7 w+ Opens a file for both writing and reading. Overwrites Syntax: pass
the existing file if the file exists. If the file does not Example: For pass statement.
for i in range(1,11):
exist, creates a new file for reading and writing. if i%2==0: # check if the number is even
pass # (No operation)
8 wb+ Opens a file for both writing and reading in binary else:
format. Overwrites the existing file if the file exists. If print("Odd Numbers: ",i)
the file does not exist, creates a new file for reading and Output:
writing. Odd Numbers: 1
Odd Numbers: 3
Odd Numbers: 5
9 a Opens a file for appending. The file pointer is at the end
Odd Numbers: 9
of the file if the file exists. Odd Numbers: 7

Page No: 7 | 20 Page No: 8 | 20


MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________
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
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
with different number of arguments.
Example:
for i in range(1, 4):
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
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
1 is a very important part of OOP since it is the feature that makes inheritance exploit
2 its full power. Through method overriding a class may "copy" another class, avoiding
3 duplicated code, and at the same time enhance or customize part of it.
Finally Exit
c) T = ('spam, Spam', SPAM!', 'SaPm') 4M Example: For method overriding.
print (T [2]) class A: # parent class
print (T[-2]) "Parent Class"
print (T[2:])
def display(self):
print (List (T))
Input
print ('This is base class.')
Ans Each Print
T = ('spam’, ‘Spam', ‘SPAM!', 'SaPm') class B(A): #derived class
Statement/
"Child/Derived class"
output for 1 M
Python statement Output def display(self):
print (T [2]) SPAM! print ('This is derived class.')
print (T[-2]) SPAM! obj = B() # instance of child
print (T[2:]) [‘SPAM!', 'SaPm'] obj.display() # child calls overridden method
print (list (T)) ['spam', 'Spam', 'SPAM!', 'SaPm'] Output:
This is derived class.

d) Explain method overloading and overriding 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
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
arguments given. Method overloading is a concept in which a method in a class performs 2M
Dictionary.
operations according to the parameters passed to it. Python does not support method and Overriding
overloading, that is, it is not possible to define more than one method with the same name in 2M Ans pop(): We can remove a particular item in a dictionary by using the method pop(). Any two
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
accepting one argument can be called with an integer value, a string or a double as shown in Example: each
next example.
>>> squares
class Demo:
def method(self, a): {1: 1, 2: 4, 3: 9, 4: 16}
print(a) >>> squares.pop(2) # remove a particular item
obj= Demo( ) 4
obj.method(50) >>> squares
obj.method('Meenakshi') {1: 1, 3: 9, 4: 16}
obj.method(100.2)
Output: Popitem(): The method, popitem() can be used to remove and return an arbitrary item
50 (key, value) form the dictionary.
Meenakshi Example:
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: 9 | 20 Page No: 10 | 20
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________
>>> print(squares.popitem()) # remove an arbitrary item
(5, 25)
>>> squares
{1: 1, 2: 4, 3: 9, 4: 16}

Clear(): All the items can be removed at once using the clear() method.
Example:
>>> squares
{1: 1, 4: 16}
>>> squares.clear() # removes all items
>>> squares  A one dimensional array has one axis indicated by Axis-0. That axis has five
{} elements in it, so we say it has length of five.
 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
dictionary itself. dimensional array has three elements, so its length it three and Axis-1 has six
Example: elements, so its length is six.
>>> squares
{1: 1, 3: 9, 4: 16} Execute Following command to install numpy in window, Linux and MAC OS:
>>> del squares[3] # delete a particular item
>>> squares python -m pip install numpy
{1: 1, 4: 16} To use NumPy you need to import Numpy:
import numpy as np # alias np
Using NumPy, a developer can perform the following operations:
b) Explain Numpy package in detail. 4M 1. Mathematical and logical operations on arrays.
2. Fourier transforms and routines for shape manipulation.
Ans  NumPy is the fundamental package for scientific computing with Python. Suitable 3. Operations related to linear algebra.
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.
multidimensional array object, and tools for working with these arrays. M
 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
by a tuple of positive integers and represented by a single variable. NumPy's python with example.
array class is called ndarray. It is also known by the alias array.
 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()
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
of dimensions. And it’s cursor, who decides from where data has to be read or write in a file. and for Tell()
 In NumPy, dimensions are called axes. Each dimension of an array has a length Syntax: method 2 M
f.seek(offset, fromwhere)
which is the total number of elements in that direction. where offset represents how many bytes to move fromwhere, represents the position from
 The size of an array is the total number of elements contained in an array in all where the bytes are moving.
the dimension. The size of NumPy arrays are fixed; once created it cannot be Example:
changed again. f = open("demofile.txt", "r")
 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
advantages of Numpy arrays are that they are fast, easy to work with, and give print(f.readline())
users the opportunity to perform calculations across entire arrays.
tell(): tell() returns the current position of the file pointer from the beginning of the file.
Syntax: file.tell()
 Fig. shows the axes (or dimensions) and lengths of two example arrays; (a) is
Example:
a one-dimensional array and (b) is a two-dimensional array. f = open("demofile.txt", "r")
# points at the start
print(f.tell())

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


MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________
d) WAP to read contents of first.txt file and write same content in second.txt 4M >>> first_set ^ second_set # using the `^` operator
file. {1, 2, 3, 7, 8, 9}
b) Explain building blocks of python. 6M
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 Ans 1) Python Identifiers: Variable name is known as identifier. Any 6 building
suitable To name an identifier following are the rules: blocks=6M
with open('second.txt', 'w') as f: # Open the second file for writing  The first character of the variable must be an alphabet or underscore ( _ ).
program 4 M
f.write(contents) # Write the contents of the first file to the second file  All the characters except the first character may be an alphabet of lower-case(a-z),
upper-case (A-Z), underscore or digit (0-9).
 Identifier name must not contain any white-space, or special character (!, @, #, %, ^,
5. Attempt any TWO of the following: 12 M &, *).
 Identifier name must not be similar to any keyword defined in the language. o
a) Explain any four set operations with example. 6M Identifier names are case sensitive for example my name, and MyName is not the
same.
Ans Set Operations: Each operation Eg: a,b,c=5,10,15
1. Set Union: The union of two sets is the set of all the elements of both the sets without -1 ½ M
duplicates. You can use the ‘|’ operator to find the union of a Python set. 2) Reserved Words
>>> first_set = {1, 2, 3} The following list shows the Python keywords. These are reserved words and cannot use
>>> second_set = {3, 4, 5} them as constant or variable or any other identifier names. All the Python keywords contain
>>> first_set.union(second_set) lowercase letters only.
{1, 2, 3, 4, 5}
>>> first_set | second_set # using the ‘|’ operator
{1, 2, 3, 4, 5}

2. Set Intersection: The intersection of two sets is the set of all the common elements of
both the sets. You can use the ‘&’ operator to find the intersection of a Python set.
>>> first_set = {1, 2, 3, 4, 5, 6}
>>> second_set = {4, 5, 6, 7, 8, 9}
>>> first_set.intersection(second_set)
{4, 5, 6}
>>> first_set & second_set # using the ‘&’ operator
{4, 5, 6}

3. Set Difference
The difference between two sets is the set of all the elements in first set that are not present
in the second set. You would use the ‘–‘ operator to achieve this in Python. 3) Indentation: Python provides no braces to indicate blocks of code for class and function
>>> first_set = {1, 2, 3, 4, 5, 6} definitions or flow control. Blocks of code are denoted by line indentation, which is
>>> second_set = {4, 5, 6, 7, 8, 9} compulsory.
>>> first_set.difference(second_set) The number of spaces in the indentation is variable, but all statements within the block
{1, 2, 3} must be indented the same amount. For example –
>>> first_set - second_set # using the ‘-‘ operator
{1, 2, 3} if True:
>>> second_set - first_set print "True"
{8, 9, 7} else:
print "False"
4. Set Symmetric Difference: The symmetric difference between two sets is the set of all
the elements that are either in the first set or the second set but not in both. You have the Thus, in Python all the continuous lines indented with same number of spaces would form
choice of using either the symmetric_difference() method or the ^ operator to do this in a block.
Python.
>>> first_set = {1, 2, 3, 4, 5, 6} 4) Python Types: The basic types in Python are String (str), Integer (int), Float
>>> second_set = {4, 5, 6, 7, 8, 9} (float), and Boolean (bool). There are also built in data structures to know when you
>>> first_set.symmetric_difference(second_set) learn Python. These data structures are made up of the basic types, you can think of
{1, 2, 3, 7, 8, 9} them like Legos, the data structures are made out of these basic types. The core data
Page No: 13 | 20 Page No: 14 | 20
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________
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
(set). can only store one of an element. Sets are declared with curly braces like
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
other programming languages, characters in strings may be accessed as if from a set.
accessing an array. In the example below we’ll assign a string to a variable,
access the first element, check for a # we can turn a list into a set
substring, and check the length of the string. x = ['a', 'a', 'b', 'c', 'c']
x = 'abcd' x = set(x)

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
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
example code we’ll explore how these numbers can interact.
statements, for and while loops, and try-except blocks.
x = 2.5
y=2
6) Functions: Functions are reusable blocks of code that perform specific tasks. In
Python, functions are defined using the def keyword.
Boolean: Boolean variables in Python are either True or False. They will also
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
Dictionaries: Dictionaries in Python are a group of key-value pairs. def get_student_details(self): (Any
Dictionaries are declared with curly braces and their entries can be accessed return f"Name: {self.name}\nGender: {self.gender}\nYear: {self.year}" Similar/Suitable
in two ways, a) with brackets, and b) with .get. The example code shows how other
we can access items in a dictionary. logic/program
# faculty.py can consider)
_dict = { class Faculty:
'a': 'Sally sells sea shells', def __init__(self, faculty):
'b': 'down by the seashore' self.name = faculty['name']
} self.subject = faculty['subject']

Tuples: Tuples is an immutable sequence in Python. Unlike lists, you can’t move def get_faculty_details(self):
objects out of order in a Tuple. Tuples are declared with parenthesis and must return f"Name: {self.name}\nSubject: {self.subject}"
contain a comma (even if it is a tuple of 1). The example below shows how to add
tuples, get a tuple from a list, and return information about it. # testing.py
x = (a, b) # importing the Student and Faculty classes from respective files
from student import Student
from faculty import Faculty
Page No: 15 | 20 Page No: 16 | 20
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________
Ans class Animal: #super class Any other
# creating dicts for student and faculty suitable
student_dict = {'name' : 'ABC', 'gender': 'Male', 'year': '3'} # attribute and method of the parent class program can
faculty_dict = {'name': 'XYZ', 'subject': 'Programming'} name = "" consider
def eat(self):
# creating instances of the Student and Faculty classes print("I can eat")
student = Student(student_dict)
# inherit from Animal Class creation:
faculty = Faculty(faculty_dict)
class Dog(Animal): sub(2 M class 2m
# getting and printing the student and faculty details Inherit one
print(student.get_student_details()) # new method in subclass
class to another:
print() def display(self):
2m
print(faculty.get_faculty_details()) # access name attribute of superclass using self
print("My name is ", self.name) Logic: 2m

Output : # create an object of the subclass


Name: ABC labrador = Dog()
Gender: Male
Year: 3 # access superclass attribute and method
labrador.name = "Rohu"
Name: XYZ
Subject: Programming
labrador.eat()
# call subclass method
labrador.display()
6. Attempt any TWO of the following: 12 M
Output:
a) Write a program to create class student with Roll no. and Name and 6M I can eat
display its contents My name is Rohu

Ans class Student: Create Class:


def __init__(self, name, rollno): 3m c) List and explain any four built-in functions on set. 6M
self.name = name
self.rollno = rollno Display Ans Built-in Functions with Set Listing: 2m
Method: 3m add()
discard() Explanation of
def __str__(self): any two
return f"{self.name}({self.rollno})" copy()
remove() function: 4m
clear()
(2 M each)
s1 = Student("ABC", 32) union()
print(s1) difference()
intersection()
Output: discard()
ABC 32 issubset()
issuperset()
b) Write program to implement concept of inheritance in python. 6M pop()
update()
symmetric_difference()

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


MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________
add(): copy(): Returns a shallow copy of the set
Adds an element to the set. If an element is already exist in the set, then it does not Example:
add that element. s = {'g', 'e', 'k', 's'}
Example: p=s.copy()
s = {'g', 'e', 'k', 's'} print("original set:",s)
# adding f into set s print("Copied set:",p)
s.add('f')
print('Set after updating:', s) Output:
original set: {'k', 's', 'g', 'e'}
output: Copied set: {'k', 's', 'g', 'e'}
Set after updating: {'s', 'f', 'e', 'g', 'k'}

discard(): Union():The set.union() method returns a new set with distinct elements from all the
Removes the element from the set given sets.
Example: Example:
s = {'g', 'e', 'k', 's'} nums1 = {1, 2, 2, 3, 4, 5}
print('Set before discard:', s) nums2 = {4, 5, 6, 7, 7, 8}
s.discard('g') distinct_nums = nums1.union(nums2)
print('\nSet after discard g:', s) print("The union of two sets is: ", distinct_nums)

Output: Output:
Set before discard: {'s', 'e', 'k', 'g'} The union of two sets is: {1, 2, 3, 4, 5, 6, 7, 8}
Set after discard g: {'s', 'e', 'k'}
Difference():The set.difference() method returns the new set with the unique elements
remove(): that are not in the other set passed as a parameter.
Removes the specified element from the set. If the specified element not found, raise Example:
an error. nums1 = {1, 2, 2, 3, 4, 5}
Example: nums2 = {4, 5, 6, 7, 8, 8}
s = {'g', 'e', 'k', 's'} nums3 = nums1.difference(nums2)
print('Set before remove:', s) nums4 = nums2.difference(nums1)
s.remove('e') print("nums1 - nums2: ", nums3)
print('\nSet after remove e:', s) print("nums2 - nums1: ", nums4)

Output: Output:
Set before remove: {'s', 'k', 'e', 'g'} nums1 - nums2: {1, 2, 3}
Set after remove e: {'s', 'k', 'g'} nums2 - nums1: {8, 6, 7}

clear(): Intersection():The set.intersection() method returns a new set with the elements that
Removes all elements from the set are common in the given sets.
Example: Example:
s = {'g', 'e', 'k', 's'} x = {"apple", "banana", "cherry"}
print('Set before clear:', s) y = {"google", "microsoft", "apple"}
s.clear() z = x.intersection(y)
print('\nSet after clear:', s) print(z)
Output:
Set before clear: {'g', 'k', 's', 'e'} Output:
Set after clear: set() apple

Page No: 19 | 20 Page No: 20 | 20


MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous)
(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
understanding level of the candidate.
c) Describe Tuples in Python. 2M
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.
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.
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
candidate’s understanding. take any number of arguments, but can only have one expression.
7) For programming language papers, credit may be given to any other program based on equivalent concept. Syntax: lambda arguments : expression
8) As per the policy decision of Maharashtra State Government, teaching in English/Marathi and Bilingual (English + Example: x= lambda a,b : 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
Output: 50
+Marathi), the Examiner shall consider the same and assess the answer based on matching of concepts with
model answer. e) Write syntax of defining class in Python. 2M

Q. Sub Answer Marking Ans class <ClassName>: 2M for syntax


No. Q. Scheme <statement1>
N. <statement2>
.
1 Attempt any FIVE of the following: 10 M
.
a) List Python features. (Any four) 2M <statementN>

f) List file operations in Python. 2M


Ans  Easy to Learn and Use 2M (1/2 M each)
 Interactive Mode Any Four
 Expressive Language Ans  Opening file (using open() function) 2M
 Interpreted Language  Reading file (using read() function)
 Cross-platform Language  Writing file (using write() function)
 Portable  Copy files
 Free and Open Source  Delete files (using remove() function)
 Closing file (Using close() function)
 Object-Oriented Language
g) Describe indentation in Python. 2M
 Extensible
 Large Standard Library Ans Indentation refers to the spaces at the beginning of a code line. Python indentation 2M
 GUI Programming Support refers to adding white space before a statement to a particular block of code. In another
 Integrated word, all the statements with the same space to the right, belong to the same code
 Databases block.
 Scalable
b) List comparision operators in Python. 2M

Ans Comparison operators in Python are 2M (1M each)

Operator Meaning www.diplomachakhazana.in


== Equal to
Page No: 1 | 21 Page No: 2 | 21
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________
Shift value is moved 1010 << 2
left by the =101000 =
number of bits 40
specified by the
right operand.
>> Binary Right The left operand's a>>2 =
Shift value is moved 1010 >> 2
right by the =0010 = 2
number of bits
2. Attempt any THREE of the following: 12 M specified by the
right operand.
a) Describe bitwise operators in Python with example. 4M b) Write any four methods of dictionary. 4M

Ans Bitwise operators acts on bits and performs bit by bit operation. Assume a=10 (1010) 4M (for any Ans 4M (any four,
and b=4 (0100) four, 1M each) 1M each)
Operator Meaning Description Example
& Binary AND This operation a &b =
performs AND 1010 &
operation 0100 =
between 0000 =0
operands.
Operator copies a
bit, to the result,
if it exists in both
operands
| Binary OR This operation a|b = 1010 |
performs OR 0100 =
operation 1110 = 14
between
operands. It
copies a bit, if it
exists in either
operand.
^ Binary XOR This operation a^b=1010 ^
performs XOR 0100 =
operations 1110 =14
between
operands. It
copies the bit, if it
is set in one
operand but not
both.
~ Binary Ones It is unary ~a= ~ 1010
Complement operator and has = 0101
the effect of www.diplomachakhazna.in
'flipping' bits i.e.
opposite the bits
of operand.
<< Binary Left The left operand's a<<2 =
Page No: 3 | 21 Page No: 4 | 21
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________

test()
print("global variable=",g)

output:
local variable= 20
Global variable= 10
global variable= 10

d) Write python program to illustrate if else ladder. 4M

Ans i = 20 4M (for correct


if (i == 10): program and
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: 5 | 21 Page No: 6 | 21


www.diplomachakhazana.in
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous)
(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.
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).
position. We
>>> list= [10, 20, 30, 40]
can also remove the items from the list using remove() or pop() or del statement.
>>> list
[10, 20, 30, 40]
>>> list1= [10, 20, 30, 40, 50]
30
>>> list1
>>> list
[10, 20, 30, 40, 50]
[10, 20, 40]
>>> list1[0]=0 # change 0th index element
>>> list.pop()
>>> list1
40
[0, 20, 30, 40, 50]
>>> list
>>> list1[-1]=60 # change last index element
[10, 30]
>>> list1
We can delete one or more items from a list using the keyword del. It can even delete
[0, 20, 30, 40, 60]
the list entirely. But it does not store the value for further use
>>> list1[1]=[5,10] # change 1st index element as sublist
>>> list= [10, 20, 30, 40]
>>> list1
>>> list
[0, [5, 10], 30, 40, 60]
[10, 20, 30, 40]
>>> list1[1:1]=[3,4] # add elements to a list at the desired location
>>> del (list[1]) # del() with index
>>> list1
>>> list
[0, 3, 4, [5, 10], 30, 40, 60]
[10, 30, 40]
>>> del list[2] # del with index
>>> list 4 Indexing
There are various ways in which we can access the elements of a list.
[10, 30]
List Index: We can use the index operator [] to access an item in a list. Index starts
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.
use the remove() method if we know the item that we want to remove or delete from the
Example:
list (but not the index).
>>> list1=[10,20,30,40,50]
>>> list=[10,"one",20,"two"]
>>> list1[0]
>>> list.remove(20)
10
>>> list >>> list1[4]
[10, 'one', 'two'] 50
>>> list.remove("one") >>> list1[1:3]
>>> list [20, 30]
[10, 'two']
>>> 5. List Slicing
The slicing operator returns a subset of a list called slice by specifying two indices, i.e.
3. Updating Lists: start and end.
• List are mutable, meaning their elements can be changed or updated unlike string or Syntax:
tuple. List_variable[start_index:end_index]
• Mutability is the ability for certain types of data to be changed without entirely Example:
recreating it. Using >>> l1=([10,20,30,40,50])
mutable data types can allow programs to operate quickly and efficiently. >>> l1[1:4]
[20, 30, 40]
Page No: 7 | 21 Page No: 8 | 21
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________
class Demo:
def method(self, a):
b) Write Python code for finding greatest among four numbers. 4M print(a)
obj= Demo()
Ans list1 = [ ] Any correct
logic program obj.method(50)
num = int(input("Enter number of elements in list: "))
4M obj.method('Meenakshi')
for i in range(1, num + 1):
obj.method(100.2)
element = int(input("Enter elements: "))
Output:
list1.append(element)
50
print("Largest element is:", max(list1))
Meenakshi
Output:
100.2
Enter number of elements in list: 4
d) Explain how try-catch block is used for exception handling in python. 4M
Enter elements: 10
Enter elements: 20 Ans • In Python, exceptions can be handled using a try statement. A try block Proper
Enter elements: 45 consisting of one or more statements is used by programmers to partition code explanation
Enter elements: 20 that might be affected by an exception.
Largest element is: 45 • A critical operation which can raise exception is placed inside the try clause and the 4 M
c) Illustrate with example method over loading. 4M code that handles exception is written in except clause.
• The associated except blocks are used to handle any resulting exceptions thrown in
Ans • Method overloading is the ability to define the method with the same name but with a Explanation the try block. That is we want the try block to succeed and if it does not succeed, we
different number of arguments and data types. 1 M and want to control to pass to the catch block.
• With this ability one method can perform different tasks, depending on the number of Example 3 M • If any statement within the try block throws an exception, control immediately shifts
arguments or the types of the arguments given. to the catch block. If no exception is thrown in the try block, the catch block is skipped.
• Method overloading is a concept in which a method in a class performs operations • There can be one or more except blocks. Multiple except blocks with different
according to the parameters passed to it. exception names can be chained together.
Example: With a method to perform different operations using method overloading. • The except blocks are evaluated from top to bottom in the code, but only one except
class operation: block is executed for each exception that is thrown.
def add(self,a,b): • The first except block that specifies the exact exception name of the thrown exception
return a+b is executed. If no except block specifies a matching exception name then an except
block that does not have an exception name is selected, if one is present in the code.
op1=operation()
• For handling exception in Python, the exception handler block needs to be written
# To add two integer numbers
which consists of set of statements that need to be executed according to raised
print("Addition of integer numbers=",op1.add(10,20)) exception. There are three blocks that are used in the exception handling process,
# To add two floting point numbers namely, try, except and finally.
print("Addition of integer numbers=",op1.add(11.12,12.13)) 1. try Block: A set of statements that may cause error during runtime are to be written
# To add two strings in the try
print("Addition of integer numbers=",op1.add("Hello","Python")) block.
Output: 2. except Block: It is written to display the execution details to the user when certain
Addition of integer numbers= 30 exception occurs in the program. The except block executed only when a certain type as
Addition of integer numbers= 23.25 exception occurs in the execution of statements written in the try block.
Addition of integer numbers= HelloPython
Python does not support method overloading, that is, it is not possible to define more Syntax:
than one method with the same name in a class in Python. try:
• This is because method arguments in python do not have a type. A method accepting D the operations here
one argument can be called with an integer value, a string or a double as shown in next ......................
example.
Page No: 9 | 21 Page No: 10 | 21
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________
except Exception1: Ans Python Command line arguments are input parameters passed to the script when 1 M for
If there is Exception1, then execute this block. executing them. Almost all programming language provide support for command line definition and
except Exception2: arguments. Then we also have command line options to set some specific options for 3 M for
the program. program
If there is Exception2, then execute this block.
...................... There are many options to read python command line arguments. The three most
else: common ones are:
If there is no exception then execute this block. Python sys.argv
Python getopt module
Example: For try-except clause/statement. Python argparse module
n=10
m=0 Program:
try: import sys
n/m x=int(sys.argv[1])
except ZeroDivisionError: y=int(sys.argv[2])
print("Divide by zero error") sum=x+y
else: print("The addition is :",sum)
print (n/m)
Output:
Output:
Divide by zero error
C:\Python34\python sum.py 6 4
The addition is : 10
4. Attempt any THREE of the following: 12 M c) Write python code to count frequency of each characters in a given file. 4M
a) Compare list and dictionary. (Any 4 points) 4M Ans import collections Any proper
import pprint logic program
Ans List Dictionary Any four point, file_input = input('File Name: ') 4M

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:
as that of array in c++. key and value pairs. count = collections.Counter(info.read().upper())
value = pprint.pformat(count)
List is created by placing elements in [ ] Dictionary is created by placing print(value)
separated by commas “, “ elements in { } as “key”:”value”,
d) Write python program to read contents of abc.txt and write same content to 4M
each key value pair is separated by
commas “, “ pqr.txt.

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
from 0. data type. # read content from first file logic program
for line in firstfile: for 4 M
The elements are accessed via indices. The elements are accessed via key- # write content to second file
values. secondfile.write(line)
The order of the elements entered are There is no guarantee for
maintained. maintaining order.
5. Attempt any TWO of the following: 12 M
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
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: 11 | 21 Page No: 12 | 21
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous)
(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
 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 (" ").
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
 Dictionary: Represents a collection of data that associate a unique key with each unchangeable (immutable). Once a string is created, it cannot be modified.
value. Example: For string data type.
 Boolean: Represents truth-values (true or false). >>> s1="Hello" #string in double quotes
>>> s2='Hi' #string in single quotes
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
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
Example: For number data types are integers. >>>type(s1)
>>>a=10 <class 'str'>
>>>b -10
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
>>>type(a) datatype in Python and is very flexible.
>>> <class 'int'> List can contain heterogeneous values such as integers, floats, strings, tuples, lists and
dictionaries but they are commonly used to store collections of homogeneous objects.
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
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
1 and false is 0. pretty straight forward. Items separated by commas ( , ) are enclosed within brackets [
For example ].
>>>a = 18 > 5 Example: For list.
>>>print(a) >>> first=[10, 20, 30] # homogenous values in list
True >>> second=["One","Two","Three"] # homogenous values in list
b=2>3 >>> first
print(b) [10, 20, 30]
False >>> second
['One', 'Two', 'Three']
3. Floating-Point/Float Numbers (Float Data Type): Floating-point number or Float is >>> first + second # prints the concatenated lists
a positive or negative number with a fractional part. A floating point number is [10, 20, 30, 'One', 'Two', 'Three']
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
Example: Floating point number. difference is that tuples are immutable.
x=10.1 Tuples once created cannot be modified. It is defined within parentheses ( ) where
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
contains heterogeneous items/elements.
4. Complex Numbers (Complex Data Type): Complex numbers are written in the form, Example: For tuple.
x + yj, where x is the real part and y is the imaginary part. >>> a=(10,'abc',1+3j)
Example: >>> a
Complex number. (10, 'abc', (1+3j))
>>>x = 3+4j >>> a[0]
>>>print(x.real) 10
3.0 >>> a[0]=20
>>>print(x.imag) Traceback (most recent call last):
4.0 File "<pyshell#12>", line 1, in <module>

Page No: 13 | 21 Page No: 14 | 21


MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________
8. Dictionary: Dictionary is an unordered collection of key-value pairs. It is the same as Example module
the hash table type. The order of elements in a dictionary is undefined, but we can
Import the module named mymodule, and call the greeting function:
iterate over the following:
o The key import mymodule
o The value mymodule.greeting("ABC")
o The items (key-value pairs) in a dictionary. c) Write python program to perform following operations on Set (Instead of 6M
When we have the large amount of data, the dictionary data type is used. Items in Tuple)
dictionaries are enclosed in curly braces { } and separated by the comma (,). A colon (:)
is used to separate key from value. Values can be assigned and accessed using square i) Create set
braces ([]). ii) Access set Element
Example: For dictionary data type. iii) Update set
>>> dic1={1:"First","Second":2} iv) Delete set
>>> dic1
{1: 'First', 'Second': 2} Ans # To Create set
S={10,20,30,40,50}
>>> type(dic1) 6m for any
<class 'dict'> suitable
# To Access Elements from set
>>> dic1[3]="Third" program
print (S)
>>> dic1
{1: 'First', 'Second': 2, 3: 'Third'} #To add element into set using add method
>>> dic1.keys() S.add(60) (If students
dict_keys([1, 'Second', 3]) print(S) attempted with
>>> dic1.values() “set” give
dict_values(['First', 2, 'Third']) #To update set using update method marks as per
>>> S.update(['A','B']) marking
print(S) scheme)
b) Example module. How to define module. 6M
#To Delete element from Set using discard() method OR
Ans A module allows you to logically organize your Python code. Grouping related code 2 M for
into a module makes the code easier to understand and use. A module is a Python module S.discard(30) (If students
object with arbitrarily named attributes that you can bind and reference. explanation print(S) attempted with
“Tuple”
Simply, a module is a file consisting of Python code. A module can define functions, #To delete element from set using remove() method
classes and variables. A module can also include runnable code. S.remove('A') Then
print(S)
Example 2M-create
#To delete element from set using pop() method Tuple
The Python code for a module named aname normally resides in a file named
aname.py. Here's an example of a simple module, support.py 2 M for S.pop() 2M-Access
creating print(S) tuple
def print_func( par ): module
print "Hello : ", par output: 2M-delete
return {50, 20, 40, 10, 30} Tuple)
To create a module just save the code you want in a file with the file extension .py: {50, 20, 40, 10, 60, 30}
Example {'B', 50, 20, 'A', 40, 10, 60, 30}
Save this code in a file named mymodule.py {'B', 50, 20, 'A', 40, 10, 60}
def greeting(name): {'B', 50, 20, 40, 10, 60}
print("Hello, " + name) {50, 20, 40, 10, 60}
Now we can use the module we just created, by using the import statement: 2 M for
accessing/using (Any other suitable example can consider)
Page No: 15 | 21 Page No: 16 | 21
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________
Example:
*If students have attempted by using “Tuple” then
# int
num1 = 10
#To create tuple num2 = 100
tuple1=(10,20,30,40,50)
print (tuple1) # float
#Access tuple values a = 10.5
print (tuple1[1]) b = 8.9
print (tuple1[0:3])
# complex numbers
# deleting tuple
x = 3 + 4j
del tuple1
y = 9 + 8j
print (tuple1)
2. String
output:
(10, 20, 30, 40, 50) A string is usually a bit of text (sequence of characters). In Python we use ” (double
20 quotes) or ‘ (single quotes) to represent a string.
(10, 20, 30)
There are several ways to create strings in Python:
Traceback (most recent call last):
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 (tuple1) 2. We can use ” (double quotes), see the string str2 in the source code below.
NameError: name 'tuple1' is not defined. Did you mean: 'tuple'? 3. Triple double quotes “”” and triple single quotes ”’ are used for creating multi-line
strings in Python.
Example:
str = 'beginnersbook'
6. Attempt any TWO of the following: 12 M str2 = "Chaitanya"
# multi-line string
a) Explain mutable and immutable data structures. 6M str3 = """Welcome to
Pythonsbook"""
Ans The data types in Python are divided in two categories: 3m for mutable
Immutable data types – Values cannot be changed. Immutable data types in Python are data structure str4 = '''This is a tech
1. Numbers and 3m for paper'''
2. String immutable data
3. Tuple structure
Mutable data types – Values can be changed. Mutable data types in Python are: 3. Tuple
1. List
In Python, a tuple is similar to List except that the objects in tuple are immutable which
2. Dictionaries
means we cannot change the elements of a tuple once assigned. On the other hand, we
3. Sets
can change the elements of a list.
1. Numbers To create a tuple in Python, place all the elements in a () parenthesis, separated by
Python supports integers, floats and complex numbers. commas. A tuple can have heterogeneous data items, a tuple can have string and list as
An integer is a number without decimal point for example 5, 6, 10 etc. data items as well.
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
my_data = ("hi", "hello", "bye")
Page No: 17 | 21 Page No: 18 | 21
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________
Create suitable method for reading and printing students details.
# tuple of int, float, string
my_data2 = (1, 2.8, "Hello World") Ans class Student: 2 M for class
definition
def getStudentDetails(self):
# tuple of string and list
my_data3 = ("Book", [1, 2, 3]) self.rollno=input("Enter Roll Number : ")

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


# nested tuple
self.address =input("Enter Address : ")
my_data4 = ((2, 3, 4), (1, 2, "hi"))
def printStudentDetails(self):
4. List 2 M to define
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
data type which means you can have different-2 data types under a list, for example we
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
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________
SUMMER – 2023 EXAMINATION
# function feed Model Answer – Only for the Use of RAC Assessors
def feed(self):
print("I eat only plants. I am vegetarian.") Subject Name: Programming with Python Subject Code: 22616

herbi = Herbivorous() Important Instructions to examiners: XXXXX


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

Q. Sub Answer Marking


No. Q. Scheme
N.

1 Attempt any FIVE of the following: 10 M

a) List features of Python. 2M

Ans Features of Python are listed below: Any 2,


• Easy to Learn and Use 1 M each
• Interpreted Language
• Interactive Mode
• Free and Open Source
• Platform Independence/Cross-platform Language/Portable
• Object-Oriented Language
• Extensible
b) Describe membership operators in python 2M

Ans • The membership operators in Python are used to find the existence of a particular 2 M for
element in the sequence, and used only with sequences like string, tuple, list, proper
dictionary etc. explanation
• Membership operators are used to check an item or an element that is part of a
string, a list or a tuple. A membership operator reduces the effort of searching an
element in the list.

Page No: 21 | 21 Page No: 1 | 24


MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________
• Python provides ‘in’ and ‘not in’ operators which are called membership Example:
operators and used to test whether a value or variable is in a sequence. dict={'id':'11','name':'vijay'}
print(dict)
c) Write down the output of the following Python code 2M
>>>indices-['zero','one','two',' three,' four, five'] ={'id': '11', 'name': 'vijay'}
i) >>>indices[:4] • chr(x): Converts an integer to a character.
ii) >>>indices[:-2] Example: x=chr(65) = ‘A’
• unichr(x): Converts an integer to a Unicode character
Ans Output as follows: 1 M for Example: x=unichr(65) =u’A’
i) >>>indices[:4] each
• ord(x): Converts a single character to its integer value.
[zero, one, two, three] correct
Example: x=ord('A')= 65
ii) >>>indices[:-2] output
• hex(x): Converts an integer to a hexadecimal string.
[zero, one, two, three]
Example: x=hex(12) = 0xc
d) Describe any two data conversion function. 2M • oct(x): Converts an integer to an octal string.
Example: x=oct(8) = 0o10
Ans • int(x [,base]): Converts x to an integer. base specifies the base if x is a Any 2
string. Conversion e) With neat example explain default constructor concept in Python. 2M
Example: x=int('1100',base=2)=12 function
Ans The default constructor is simple constructor which does not accept any arguments. It’s Explanation
• long(x [,base]): Converts x to a long integer. base specifies the base if x is 2M
1 M,
definition has only one argument which is a reference to the instance being constructed.
a string. Example
Example: x=long(‘123’base=8)=83L Example 1: Display Hello message using default constructor. 1M
• float(x): Converts x to a floating point number.
Example: x=float('123.45')=123.45 class Student:
• complex(real[,imag]) : Creates a complex number.
def _ _init_ _(self):
Example: x=complex(1,2) = (1+2j)
• str(x): Converts object x to a string representation. print("This is non parametrized constructor")
Example: x=str(10) = ‘10’
• repr(x): Converts object x to an expression string def show(self,name):
Example: x=repr(3) = 3
print("Hello",name)
• repr(x): Evaluates a string and returns an object.
Example: x=eval('1+2') = 3 s1 = Student()
• tuple(s): Converts s to a tuple
Example: s1.show("Student1")
x=tuple('123') = ('1', '2', '3')
x=tuple([123]) = (123,)
• list(s): Converts s to a list Output:
Example:
This is non parametrized constructor
x=list('123') = ['1', '2', '3']
Hello Student1
x=list(['12'] = ['12']
• set(s): Converts s to a set f) Describe mkdir() function. 2M
Example:
x=set('Python') Ans • We can make a new directory using the mkdir() method. Explanation
= {'y', 't', 'o', 'P', 'n', 'h'} • This method takes in the path of the new directory. If the full path is not specified, 2M
• dict(d): Creates a dictionary. d must be a sequence of (key, value) tuples. the new directory is created in the current working directory.

Page No: 2 | 24 Page No: 3 | 24


MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________
Syntax: os.mkdir(“newdir”) Output:

Example: i=1
i=2
>>> import os i=3
i=4
>>> os.mkdir("testdir") i=6
i=7
g) Describe Multiline comment in python. 2M i=8
i=9
Ans • In some situations, multiline documentation is required for a program. If we have 2 M for i=10
comments that extend multiple lines, one way of doing it is to use hash (#) in the proper b) Explain creating Dictionary and accessing Dictionary Elements with 4M
beginning of each line. Another way of doing this is to use quotation marks, either explanation example.
''' or """.
• Similarly, when it sees the triple quotation marks ''' it scans for the next ''' and Ans Creating Dictionary Creating
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
Example: For multiline comment. to the dictionary using operator (=). with example
• There are two ways for creation of dictionary in python. 2 M,
'''This is first python program 1. We can create a dictionary by placing a comma-separated list of key:value Accessing
Print is a statement''' pairs in curly braces{}. Each key is separated from its associated value by a Dictionary
colon: Element with
Example: For creating a dictionary using { }. example 2 M
>>> dict1={} #Empty dictionary
2. Attempt any THREE of the following: 12 M
>>> dict1
a) Describe Keyword "continue" with example. 4M {}
>>> 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
loop. 2M,
>>> dict2
• The continue statement rejects all the remaining statements in the current iteration Example
{1: 'Orange', 2: 'Mango', 3: 'Banana'}
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
Syntax: continue >>> dict3
{'name': 'vijay', 1: [10, 20]}
Example: For continue statement.
2. Python provides a build-in function dict() for creating a dictionary
i=0
Example: Creating directory using dict().
while i<10: >>> d1=dict({1:"Orange",2:"Mango",3:"Banana"})
>>> d2=dict([(1,"Red"),(2,"Yellow"),(3,"Green")])
i=i+1 >>> d3=dict(one=1, two=2, three=3)
>>> d1
if i==5:
{1: 'Orange', 2: 'Mango', 3: 'Banana'}
continue >>> d2
{1: 'Red', 2: 'Yellow', 3: 'Green'}
print("i= ",i) >>> d3
{'one': 1, 'two': 2, 'three': 3}

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


MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________
Accessing Values in a Dictionary 15
• We can access the items of a dictionary by following ways:
1. Referring to its key name, inside square brackets([]). • min(list)
Example: For accessing dictionary items [ ] using.
It returns the item that has the minimum value in a list.
>>> dict1={'name':'vijay','age':40}
>>> dict1['name'] Example:
'vijay' >>> list1
>>> dict1['adr'] [1, 2, 3, 4, 5]
Traceback (most recent call last): >>> min(list1)
File "<pyshell#79>", line 1, in <module> 1
dict1['adr']
KeyError: 'adr'
• list(seq)
>>>
Here, if we refer to a key that is not in the dictionary, you’ll get an It converts a tuple into a list.
exception. This error can be avoided by using get() method. Example:

2. Using get() method returns the value for key if key is in the dictionary, else >>> list1
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)
'vijay' It returns the absolute value of a number.
Example:
c) Explain any four Python's Built-in Function with example. 4M >>> abs(10)
10
Ans • len(list) Any 4 Built-
It returns the length of the list. in function • all()
Example: with example The all() function returns True if all items in an iterable are true, otherwise it
>>> list1 4M returns False.
[1, 2, 3, 4, 5] Example:
>>> len(list1) >>> x=[True, True, True]
5 >>> all(x)
• max(list) True
It returns the item that has the maximum value in a list
Example: • any()
>>> list1 The any() function returns True if any item in an iterable are true, otherwise it
[1, 2, 3, 4, 5] returns False. If the iterable object is empty, the any() function will return False.
>>> max(list1) Example:
5 >>> x=[True, False, True]
>>> any(x)
• sum(list) True
Calculates sum of all the elements of list.
Example: • bin()
>>>list1 The bin() function returns the binary version of a specified integer. The result
[1, 2, 3, 4, 5] will always start >>> bin(10)
>>>sum(list1) Example:

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


MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________
'0b1010' new_tup1 = tup2 logic 4 M
with the prefix 0b.
new_tup2 = tup1
• bool() return new_tup1, new_tup2
The bool() function returns the boolean value of a specified object.
Example: # Input two tuples
>>> bool(1) tuple1 = tuple(input("Enter the elements of the first tuple (separated by commas):
True ").split(","))

• exp()
tuple2 = tuple(input("Enter the elements of the second tuple (separated by commas):
The method exp() returns returns exponential of x: ex. ").split(","))
x: This is a numeric expression.

Example: # Interchange the tuples


>>> math.exp(1)
2.718281828459045 result_tuple1, result_tuple2 = interchange_tuples(tuple1, tuple2)
>>>

# Display the result


d) Write a Python program to find the factorial of a number provided by the 4M
user. print("Interchanged tuples:")

Ans num=int(input("Enter Number:")) Correct print("Tuple 1:", result_tuple1)


fact=1 program
print("Tuple 2:", result_tuple2)
if num< 0: 4M
print("Sorry, factorial does not exist for negative numbers") output:
elif num == 0: Enter the elements of the first tuple (separated by commas): 10,20
print("The factorial of 0 is 1")
else: Enter the elements of the second tuple (separated by commas): 30,40
for i in range(1,num + 1): Interchanged tuples:
fact=fact*i
print("The factorial of ",num," is ",fact) Tuple 1: ('30', '40')
Tuple 2: ('10', '20')
Output:
Enter Number: 5 b) Explain Bitwise operator in Python with appropriate example. 4M
The factorial of 5 is 120
Ans Bitwise operators available in Python: Any four
operator
1) Bitwise AND (&): Performs a bitwise AND operation on the corresponding bits (Each for 1
3. Attempt any THREE of the following: 12 M of two numbers. Each bit of the output is 1 if the corresponding bits of both M)
operands are 1; otherwise, it is 0.
a) Write a python program to input any two tuples and interchange the tuple 4M
Example:
variables.
a = 10 # binary: 1010
Ans def interchange_tuples(tup1, tup2): Any correct
programming b = 6 # binary: 0110

Page No: 8 | 24 Page No: 9 | 24


MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________
result = a & b specified number of positions. Zeros are shifted in from the left side.
print(result) # Output: 2 (binary: 0010) Example:
2) Bitwise OR (|): Performs a bitwise OR operation on the corresponding bits of two a = 10 # binary: 1010
numbers. Each bit of the output is 0 if the corresponding bits of both operands are
0; otherwise, it is 1. result = a >> 2

Example: print(result) # Output: 2 (binary: 10)

a = 10 # binary: 1010 c) With neat example differentiate between readline () and readlines ( ) 4M
functions in file-handling.
b = 6 # binary: 0110
Ans readline(): This method reads a single line from the file and returns it as a string. It moves readline()
result = a | b the file pointer to the next line after reading. If called again, it will read the subsequent explanation
print(result) # Output: 14 (binary: 1110) line. for 1 M and
Example for
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()
# Read the first line
Example: explanation
line1 = file.readline() for 1 M and
a = 10 # binary: 1010 Example for
print(line1) 1M
b = 6 # binary: 0110
result = a ^ b
# Read the second line
print(result) # Output: 12 (binary: 1100)
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)
Example:
a = 10 # binary: 1010 # Close the file
result = ~a file.close()
print(result) # Output: -11 (binary: -1011) readlines(): This method reads all lines from the file and returns them as a list of strings.
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.
number of positions. Zeros are shifted in from the right side.
Example:
Example:
# Open the file in read mode
a = 10 # binary: 1010
file = open("example.txt", "r")
result = a << 2
print(result) # Output: 40 (binary: 101000)
# Read all lines
6) Bitwise right shift (>>): Shifts the bits of the left operand to the right by a

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


MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________
lines = file.readlines() # Access the attributes using the self parameter
print(my_car.make) # Output: Toyota
# Close the file print(my_car.model) # Output: Corolla
file.close() print(my_car.year) # Output: 2022
# Print each line
for line in lines: # Call the method using the self parameter
print(line) car_info = my_car.get_info()

d) Describe 'Self Parameter with example. 4M print(car_info) # Output: Make: Toyota, Model: Corolla, Year: 2022

Ans In Python, the self parameter is a convention used in object-oriented programming (OOP) Explanation
to refer to the instance of a class within the class itself. It allows you to access the 2 M and
# 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
keyword in Python, but it is widely adopted and recommended as a convention. my_car.start_engine() # Output: Engine started!
M
Example:
class Car: 4. Attempt any THREE of the following: 12 M
def __init__(self, make, model, year): a) Differentiate between list and Tuple. 4M
self.make = make
Ans Any 4
self.model = model correct point
List Tuple 4M
self.year = year
Lists are mutable Tuples are immutable

The implication of iterations is Time- The implication of iterations is


def get_info(self): consuming comparatively Faster

info = f"Make: {self.make}, Model: {self.model}, Year: {self.year}" The list is better for performing A Tuple data type is appropriate for
operations, such as insertion and deletion. accessing the elements
return info
Lists consume more memory Tuple consumes less memory as
compared to the list
def start_engine(self): Lists have several built-in methods Tuple does not have many built-in
methods.
print("Engine started!")
Unexpected changes and errors are more In a tuple, it is hard to take place.
likely to occur
# Create an instance of the Car class
b) Explain any four file modes in Python. 4M
my_car = Car("Toyota", "Corolla", 2022)
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
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
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________
is placed at the beginning of the file. This is the default mode. if b == 0:
3 r+ Opens a file for both reading and writing. The file pointer placed at
the beginning of the file. raise MyException("Division by zero is not allowed!")
4 rb+ Opens a file for both reading and writing in binary format. The return a / b
file pointer placed at the beginning of the file.
5 w Opens a file for writing only. Overwrites the file if the file
exists. If the file does not exist, creates a new file for writing.
6 wb Opens a file for writing only in binary format. Overwrites the # Main program
file if the file exists. If the file does not exist, creates a new file
try:
for writing
7 w+ Opens a file for both writing and reading. Overwrites the num1 = int(input("Enter the numerator: "))
existing file if the file exists. If the file does not exist, creates a
new file for reading and writing. num2 = int(input("Enter the denominator: "))
8 wb+ Opens a file for both writing and reading in binary format.
Overwrites the existing file if the file exists. If the file does not
exist, creates a new file for reading result = divide_numbers(num1, num2)
and writing
9 a Opens a file for appending. The file pointer is at the end of the print("Result:", result)
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.
10 ab Opens a file for appending in binary format. The file pointer is except MyException as e:
at the end of the 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 print("Exception:", e.message)
writing
Note: Any correct program of user defined exception can be considered.
11 a+ Opens a file for both appending and reading. The file pointer
is at the end of the file if the file exists. The file opens in the Output:
append mode. If the file does not exist, it creates a new file for
reading and writing. Enter the numerator: 10
12 ab+ Opens a file for both appending and reading in binary format.
Enter the denominator: 0
The file pointer is at the end of the file if the file exists. The file
opens in the append mode. If the file does not exist, it creates Exception: Division by zero is not allowed!
a new file for reading and writing.
13 t Opens in text mode (default). Enter the numerator: 10
14 b Opens in binary mode.
Enter the denominator: 5
15 + Opens a file for updating (reading and writing).
c) Write a program to show user defined exception in Python. 4M Result: 2.0
Ans class MyException(Exception): Any correct d) Explain Module and its use in Python. 4M
logic
def __init__(self, message): program 4 M Ans Modules are primarily the (.py) files which contain Python programming code defining Explanation
functions, class, variables, etc. with a suffix .py appended in its file name. 2 M and use
self.message = message
2M
• A file containing .py python code is called a module.
• If we want to write a longer program, we can use file where we can do editing,
# Function that raises the custom exception correction. This is known as creating a script. As the program gets longer, we may want
def divide_numbers(a, b): to split it into several files for easier maintenance.
• We may also want to use a function that you’ve written in several programs without
Page No: 14 | 24 Page No: 15 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________
copying its definition into each program. print("The string is not a palindrome.")
• In Python we can put definitions in a file and use them in a script or in an interactive output:
instance of the interpreter. Such a file is called a module.
Enter a string: madam
Use of module in python :
The string is a palindrome.
Code organization: Modules allow you to organize related code into separate files,
making it easier to navigate and maintain large projects. Enter a string: abc

Code reusability: Modules can be imported and reused in multiple programs, enabling The string is not a palindrome.
code reuse and reducing duplication.
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.
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
for the names defined within the module. # Convert the number to a string program 6M.
num_str = str(number)

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

a) Write a Python Program to check if a string is palindrome Or not. 6M digit_sum = 0


# Iterate over each character in the string
Ans def is_palindrome(string): Any correct
logic for digit in num_str:
# Remove whitespace and convert to lowercase program 6M.
# Convert the character back to an integer and add it to the sum
string = string.replace(" ", "").lower()
digit_sum += int(digit)
# Reverse the string
# Return the sum of the digits
reversed_string = string[::-1]
return digit_sum
# Check if the original and reversed strings are the same
# Test the function
if string == reversed_string:
input_number = int(input("Enter a number: "))
return True
sum_of_digits = calculate_digit_sum(input_number)
else:
print("Sum of digits:", sum_of_digits)
return False
output:
# Test the function
Enter a number: 123
input_string = input("Enter a string: ")
Sum of digits: 6
if is_palindrome(input_string):
c) Write a Python Program to accept values from user in a list and find the 6M
print("The string is a palindrome.")
largest number and smallest number in a list.
else:
Ans list = [] Any correct
logic
Page No: 16 | 24 Page No: 17 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________
num = int(input('How many numbers: ')) program 6M set1 = {1, 2, 3}

for n in range(num): set2 = {2, 3, 4}

numbers = int(input('Enter number ')) intersection_set = set1.intersection(set2)

list.append(numbers) print(intersection_set) # Output: {2, 3}

print("Maximum element in the list is :", max(list), "\nMinimum element in the list is :", 3) Difference:
min(list)) Difference operation on two sets set1 and set2 returns all the elements which are
output: present on set1 but not in set2.
Example:
How many numbers: 5
set1 = {1, 2, 3, 4, 5}
Enter number 10
set2 = {3, 4}
Enter number 20
difference_set = set1.difference(set2)
Enter number 30
print(difference_set) # Output: {1, 2, 5}
Enter number 40
4) add(element):
Enter number 50
This function adds an element to a set.
Maximum element in the list is : 50
Example:
Minimum element in the list is : 10
fruits = {"apple", "banana", "cherry"}
fruits.add("orange")
6. Attempt any TWO of the following: 12 M
print(fruits) # Output: {'apple', 'banana', 'cherry', 'orange'}
a) Explain any six set function with example. 6M

Ans 1) union():Return a new set containing the union of two or more sets 1 function
5) remove(element):
for 1 M each
Example:
This function removes an element from a set.
set1 = {1, 2, 3}
Example:
set2 = {3, 4, 5}
numbers = {1, 2, 3, 4, 5}
union_set = set1.union(set2)
numbers.remove(3)
print(union_set) # Output: {1, 2, 3, 4, 5}
print(numbers) # Output: {1, 2, 4, 5}
2) Intersection:
6) clear():
Intersection operation performed on two sets returns all the elements which are
This function removes all elements from a set, making it an empty set.
common or in both the sets.
Example:
Example:
numbers = {1, 2, 3, 4, 5}

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


MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________
numbers.clear() set1.update(set2)
print(numbers) # Output: set()
print(set1) # Output: {1, 2, 3, 4, 5}
7) isdisjoint():
The isdisjoint() method in Python's set class is used to check whether two sets b) Design a class student with data members : name, roll no., department, 6M
have any common elements. It returns True if the sets are disjoint (i.e., they have mobile no. Create suitable methods for reading and printing student
no common elements), and False otherwise. information.
Example:
# Example 1 Ans class Student: Any correct
set1 = {1, 2, 3, 4} logic
set2 = {5, 6, 7} def __init__(self): program 6
set3 = {3, 4, 5} M
self.name = ""
print(set1.isdisjoint(set2)) # True, no common elements self.roll_no = ""
print(set1.isdisjoint(set3)) # False, both sets have elements 3 and 4
self.department = ""

# Example 2 self.mobile_no = ""


fruits = {"apple", "banana", "orange"}
colors = {"red", "green", "blue"}
def read_student_info(self):
print(fruits.isdisjoint(colors)) # True, no common elements
self.name = input("Enter student name: ")

# Example 3 self.roll_no = input("Enter roll number: ")


setA = {1, 2, 3} self.department = input("Enter department: ")
setB = {4, 5, 6}
self.mobile_no = input("Enter mobile number: ")
print(setA.isdisjoint(setB)) # True, no common elements

8) pop():method in Python's set class is used to remove and return an arbitrary


def print_student_info(self):
element from the set. Since sets are unordered collections, there is no guarantee
on which element will be popped. print("Student Information:")
Example:
fruits = {"apple", "banana", "orange", "grape"} print("Name:", self.name)

# Remove and return an arbitrary element from the set print("Roll Number:", self.roll_no)
popped_element = fruits.pop()
print("Department:", self.department)
print(popped_element) # Output: an arbitrary element from the set print("Mobile Number:", self.mobile_no)
print(fruits) # Output: the modified set after popping an element

9) update():The update() method in Python's set class is used to update a set by


adding elements from another iterable or set. It modifies the set in place by adding # Create an instance of the Student class
all the elements from the iterable or set specified. student = Student()
Example:
set1 = {1, 2, 3}
set2 = {3, 4, 5}

Page No: 20 | 24 Page No: 21 | 24


MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________
# Read and set student information Example:
student.read_student_info() # Base class
class Animal:
# Print student information def __init__(self, name):
student.print_student_info() self.name = name
output:
Enter student name: raj def speak(self):
Enter roll number: 11 print("Animal speaks")
Enter department: computer
Enter mobile number: 123456 # Derived class inheriting from Animal
Student Information: class Dog(Animal):
Name: raj def speak(self):
Roll Number: 11 print("Dog barks")
Department: computer
Mobile Number: 123456 # Derived class inheriting from Animal

c) With suitable example explain inheritance in Python. 6M class Cat(Animal):

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
constructing classes from other classes is called inheritance. example 3 M
• 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.
dog = Dog("Buddy")
• In inheritance, the child class acquires the properties and can access all the data
members and functions defined in the parent class. A child class can also provide its cat = Cat("Whiskers")
specific implementation to the functions of the parent class.
Syntax:
# Call the speak method of the derived classes
class A:
dog.speak() # Output: Dog barks
# properties of class A
cat.speak() # Output: Cat meows
class B(A):
# class B inheriting property of class A
# more properties of class B

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


lOMoARcPSD|35683512

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


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

PWP Model Answer Summer 2022

Programming With Python (Rashtrasant Tukadoji Maharaj Nagpur University)

Page No: 24 | 24

Studocu is not sponsored or endorsed by any college or university


Downloaded by Krushna Karmalkar (krushnakarmalkar00@gmail.com)
lOMoARcPSD|35683512 lOMoARcPSD|35683512

SUMMER-2022 EXAMINATION The List has the variable The tuple has the fixed length
Subject Name: Programming with Python Model Answer Subject Code: 22616 length
List operations are more error Tuples operations are safe
Important Instructions to examiners: prone.
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
the model answer scheme. homogeneous and heterogeneous elements.
heterogeneous elements.
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.
deletion operations. operations like accessing
3. The language errors such as grammatical, spelling errors should not be given more elements.
Importance (Not applicable for subject English and Communication Skills. List iteration is slower and is Tuple iteration is faster.
4. While assessing figures, examiner may give credit for principal components time consuming.
indicated in the figure. The figures drawn by candidate and model answer may vary. d) Explain Local and Global variable 2M (1m each)
The examiner may give credit for any equivalent figure drawn. Local Variables: Local variables are those which are initialized
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
constant values may vary and there may be some difference in the candidate’s cannot be accessed anywhere outside the function
answers and model answer. Example:
def f():
6. In case of some questions credit may be given by judgement on part of examiner of
# local variable
relevant answer based on candidate’s understanding. s = "I love Python Programming"
7. For programming language papers, credit may be given to any other program based print(s)
on equivalent concept. # Driver code
f()
8. As per the policy decision of Maharashtra State Government, teaching in
Output
English/Marathi and Bilingual (English + Marathi) medium is introduced at first year I love Python Programming
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 Global Variables: The global variables are those which are defined
language (English +Marathi), the Examiner shall consider the same and assess the outside any function and which are accessible throughout the
answer based on matching of concepts with model answer. program i.e. inside and outside of every function.
Example:
# This function uses global variable s
Q. Sub Answer Marking Scheme
def f():
No. Q. N.
print("Inside Function", s)
1 Attempt Any FIVE of the following 10
a) Name different modes of Python 2M (1m each)
# Global scope
Python has two basic modes:
s = "I love Python Programming"
• Script (Normal Mode)
f()
• Interactive Mode print("Outside Function", s)
b) List identity operators in python 2M (1m each)
Identity operators in Python are Output:
• is Inside Function I love Python Programming
• is not 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
List Tuple difference, any 2 Class: A class is a user-defined blueprint or prototype from which definition: 1M
Lists are mutable Tuples are immutable difference) objects are created. Classes provide a means of bundling data Each)
Lists consume more memory Tuple consume less memory and functionality together.
as compared to the list
Lists have several built-in Tuple does not have many Object: An object is an instance of a class that has some
methods built-in methods. attributes and behavior. Objects can be used to access the
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

Downloaded by Krushna Karmalkar (krushnakarmalkar00@gmail.com) Downloaded by Krushna Karmalkar (krushnakarmalkar00@gmail.com)


lOMoARcPSD|35683512 lOMoARcPSD|35683512

f) How to give single and multiline comment in Python 2M (1m each)


Single line comment: Single-line comments are created simply by
beginning a line with the hash (#) character, and they are
automatically terminated by the end of line.
Example:
# print is a statement
print(‘Hello Python’)

Multi line comment: Python multi-line comment is a piece of text


enclosed in a delimiter (""") Triple quotation marks.
Example:
""" Multi-line comment used
print("Python Comments") """
or
To add a multiline comment you could insert a # for each line:
Example:
#This is a comment
#written in
#more than just one line
print("Hello, World!")
g) List different modes of opening file in Python 2M
Modes for opening file: (Any 2 names 2M)
• r: open an existing file for a read operation.
• w: open an existing file for a write operation. If the file
already contains some data then it will be overridden.
• a: open an existing file for append operation. It won’t
override existing data. c) Explain how to use user defined function in python with example 4M (2m for
• r+: To read and write data into the file. The previous • In Python, def keyword is used to declare user defined explanation and
functions. 2m for example)
data in the file will be overridden.
• The function name with parentheses (), which may or may
• w+: To write and read data. It will override existing data. not include parameters and arguments and a colon:
• a+: To append and read data from the file. It won’t • An indented block of statements follows the function
override existing data. name and arguments which contains the body of the
function.
2 Attempt any THREE of the following 12 Syntax:
a) Write a program to print following 4M (for correct def function_name():
1 program and statements
12 logic) .
123 .
1234 Example:
def fun():
for i in range(1,5): print(“User defined function”)
for j in range(1,i+1): fun()
print(j,end=' ') output:
print() User defined function
b) Explain four Buit-in tuple functions in python with example 4M ( 1M for each
function with Parameterized function: The function may take arguments(s) also
example) called parameters as input within the opening and closing
parentheses, just after the function name followed by a colon.
Syntax:
def function_name(argument1, argument2, ...):

Page 3 of 23 Page 4 of 23

Downloaded by Krushna Karmalkar (krushnakarmalkar00@gmail.com) Downloaded by Krushna Karmalkar (krushnakarmalkar00@gmail.com)


lOMoARcPSD|35683512 lOMoARcPSD|35683512

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.
Example: Floating point number.
Output: x=10.1
ID : 11 type(x)
Name : Vijay
<class 'float'>
3 Attempt any THREE of the following 12
a) List data types used in Python. Explain any two with 4M (2m for list, 4. Complex Numbers (Complex Data Type): Complex
example and 2m for two numbers are written in the form, x + yj, where x is the real
Data types in Python programming includes: example) part and y is the imaginary part.
• Numbers: Represents numeric data to perform Example:
mathematical operations. Complex number.
• String: Represents text characters, special symbols or >>>x = 3+4j
alphanumeric data. >>>print(x.real)
• List: Represents sequential data that the programmer 3.0
wishes to sort, merge etc. >>>print(x.imag)
• Tuple: Represents sequential data with a little 4.0
difference from list.
• Dictionary: Represents a collection of data that 5. String Data Type: String is a collection of group of
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 ("
"). Any letter, a number or a symbol could be a part of the
1. Integers (int Data Type): An integer is a whole number string. Strings are unchangeable (immutable). Once a string
that can be positive (+) or negative (−). Integers can be of any is created, it cannot be modified.
length, it is only limited by the memory available. Example: For string data type.

Page 5 of 23 Page 6 of 23

Downloaded by Krushna Karmalkar (krushnakarmalkar00@gmail.com) Downloaded by Krushna Karmalkar (krushnakarmalkar00@gmail.com)


lOMoARcPSD|35683512 lOMoARcPSD|35683512

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

Page 7 of 23 Page 8 of 23

Downloaded by Krushna Karmalkar (krushnakarmalkar00@gmail.com) Downloaded by Krushna Karmalkar (krushnakarmalkar00@gmail.com)


lOMoARcPSD|35683512 lOMoARcPSD|35683512

it item is in list or in >>> print("Hello" c=c%a


sequence. not in x)
False 7 **= Performs exponential c **= a is
(power) calculation on equivalent to
Assignment Operators (Augmented Assignment Operators): operators and assign
value to the left operand. c = c ** a
Assignment operators are used in Python programming to assign
values to variables. The assignment operator is used to store the 8 //= Performs exponential c //= a is
value on the right-hand side of the expression on the left-hand side (power) calculation on equivalent to
variable in the expression. operators and assign
For example, a = 5 is a simple assignment operator that assigns the value to the left operand. c = c // a
value 5 on the right to the variable a on the left.
There are various compound operators in Python like a += 5 that c) Explain indexing and slicing in list with example 4M: (2m for
adds to the variable and later assigns the same. It is equivalent to Indexing: An individual item in the list can be referenced by indexing and 2m
a = a + 5. using an index, which is an integer number that indicates the for slicing)
Following table shows assignment operators in Python relative position of the item in the list.
programming: There are various ways in which we can access the elements
Sr. Operator Description Example of a list some as them are given below:
No.
1. List Index: We can use the index operator [] to access an
1 = Assigns values from right c=a+b item in a list. Index starts from 0. So, a list having 5 elements
side operands to assigns value will have index from 0 to 4.
of a + b Example: For list index in list.
left side operand.
into c >>> list1=[10,20,30,40,50]
>>> list1[0]
2 += It adds right operand to c += a is 10
the left operand and equivalent to >>> list1[3:] # list[m:] will return elements indexed from mth
assign the result to left c=c+a index to last index
operand. [40, 50]
>>>list1[:4] # list[:n] will return elements indexed from first
3 −= It subtracts right operand c −= a is index to n-1th index
from the left equivalent to
[10, 20, 30, 40]
operand and assign the c=c−a >>> list1[1:3] # list[m:n] will return elements indexed from m
result to left operand. to n-1.
[20, 30]
4 *= It multiplies right operand operand and
with the left assign the >>> list1[5]
result to left Traceback (most recent call last):
operand and assign the operand. File "<pyshell#71>", line 1, in <module>
result to left operand. list1[5]
c *= a is IndexError: list index out of range
equivalent to
2. Negative Indexing: Python allows negative indexing for its
c=c*a sequences. The index of −1 refers to the last item, −2 to the
second last item and so on.
5 /= It divides left operand c /= a is
Example: For negative indexing in list.
with the right operand equivalent to
and assign the result to >>> list2=['p','y','t','h','o','n']
left operand. c=c/a >>> list2[-1]
'n'
6 %= It takes modulus using c %= a is >>> list2[-6]
two operands and assign equivalent to 'p'
the result to left operand.
>>> list2[-3:]

Page 9 of 23 Page 10 of 23

Downloaded by Krushna Karmalkar (krushnakarmalkar00@gmail.com) Downloaded by Krushna Karmalkar (krushnakarmalkar00@gmail.com)


lOMoARcPSD|35683512 lOMoARcPSD|35683512

['h', 'o', 'n'] Ans:


>>> list2[-7] 1)
Traceback (most recent call last): >>> dict1={1:"Vijay",2:"Santosh",3:"Yogita"}
File "<pyshell#76>", line 1, in <module> >>>print(dict1)
list2[-7] {1: 'Vijay', 2: 'Santosh', 3: 'Yogita'}
IndexError: list index out of range
ii)
List Slicing: Slicing is an operation that allows us to extract >>>dict1[2]="Shreyas"
elements from units. The slicing feature used by Python to >>>print(dict1)
obtain a specific subset or element of the data structure {1: 'Vijay', 2: 'Shreyas', 3: 'Yogita'}
using the colon (:) operator.
The slicing operator returns a subset of a list called slice by iii)
specifying two indices, i.e. start and end. >>>dict1.pop(1)
Syntax: list_variable[start_index:end_index] ‘Vijay'
This will return the subset of the list starting from start_index >>>print(dict1)
to one index less than that of the endind {2: 'Shreyas', 3: 'Yogita'}
Example: For slicing list. b) Explain decision making statements If-else, if-elif-else with 4M (2m for if-
>>> l1=([10,20,30,40,50]) example else and 2m for
>>> l1[1:4] The if-else statement: if statements executes when the if-elif-else)
[20, 30, 40] conditions following if is true and it does nothing when the
>>>l1[2:5] condition is false. The if-else statement takes care of a true
[30,40,50] as well as false condition.
d) Write a program for importing module for addition and 4M (for correct Syntax-1: Or Syntax-2:
subtraction of two numbers logic and If condition: If condition:
calculation.py: program) Statement(s) If_Block
def add(x,y): else: else:
return (x+y) Statement(s) else_Block
def sub(x,y): Example:
return (x-y) i=20
if(i<15):
operation.py: print(" less than 15")
import calculation else:
print("greater than 15")
print(calculation.add(1,2))
print(calculation.sub(4,2))
output:
Output: greater than 15
3 Concept Diagram:
2

4 Attempt any THREE of the following 12


a) Write a program to create dictionary of student the 4M (2m for i),
includes their ROLL NO and NAME 1m for ii) and
i) Add three students in above dictionary 1m for iii))
ii) Update name=’Shreyas’ of ROLL NO=2
iii) Delete information of ROLL NO=1

Page 11 of 23 Page 12 of 23

Downloaded by Krushna Karmalkar (krushnakarmalkar00@gmail.com) Downloaded by Krushna Karmalkar (krushnakarmalkar00@gmail.com)


lOMoARcPSD|35683512 lOMoARcPSD|35683512

c) Explain use of format() method with example 4M (2m for use


if-elif-else (ladder) statements: Here, a user can decide among The format() method formats the specified value(s) and insert and 2m for
multiple options. The if statements are executed from the top them inside the string's placeholder. example)
down. As soon as one of the conditions controlling the if is true, The placeholder is defined using curly brackets: {}.
the statement associated with that if is executed, and the rest of The format() method returns the formatted string.
the ladder is bypassed. If none of the conditions is true, then the Syntax
final else statement will be executed. string.format(value1, value2...)
Syntax:
if (condition-1): Example:
statement #named indexes:
elif (condition-2): >>>txt1 = ("My name is {fname}, I'm {age}".format(fname =
statements "abc", age = 36))
. >>>print(txt1)
. My name is abc, I'm 36
elif(condition-n):
statements #numbered indexes:
else: >>>txt2 =( "My name is {0}, I'm {1}".format("xyz",36))
statements >>>print(txt2)
My name is xyz, I'm 36
Example:
Example: #empty placeholders:
i = 20 >>>txt3 = ("My name is {}, I'm {}".format("pqr",36))
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.
else: character Set Examples
print ("i is not present") Letters: Upper case and A-Z,a-z
lower case english
output: alphabets
i is 20 Digits: all digits 0-9
Special symbols space,+,-,**,*,%,//,/,==,!=,>,<
Concept Diagram: Whitespaces Blank space,tabs
Other unicode characters All ASCII and Unicode characters
Tokens: Tokens in python are building blocks of the Python
programming language. The role letters and words play for the
English language, Similar to role token play for a python
programming language.
Python has the following tokens:
1)keywords
2)identifiers
3)literals
a)String literals
b)Numeric literals
c)Boolean Literals
d)Special literal None
Tokens Example
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

Downloaded by Krushna Karmalkar (krushnakarmalkar00@gmail.com) Downloaded by Krushna Karmalkar (krushnakarmalkar00@gmail.com)


lOMoARcPSD|35683512 lOMoARcPSD|35683512

special meaning to the return,finally,import,def Syntax-2:


language from <module_name> import <name(s)>
compiler/interpreter Example:
Identifiers: names given to def square,num=20, >>> from pkg.mod1 import m1
different parts of program a_lst=[1,2,3]; >>> m1()
like variables, functions, here square,num and a_lst are First module
object, class, names given to identifiers. >>>
different datatypes.
Literals/Constants: Data String: ‘Mayank‘,’abc‘,’anish‘; Syntax-3:
items that have fixed values Numeric: 1,1.2,4,-3.95; from <module_name> import <name> as <alt_name>
Boolean: True,False Example:
Special literal None; meaning nothing >>> from pkg.mod1 import m1 as module
e) Write a program illustrating use of user defined package in 4M (2m for >>> module()
python defining first module
A package is a hierarchical file directory structure that defines a package and 2m
single Python application environment that consists of modules You can import modules with these statements as well:
for import from <package_name> import <modules_name>[,
and subpackages and sub-subpackages, and so on. package in <module_name> ...]
Packages allow for a hierarchical structuring of the module program) from <package_name> import <module_name> as <alt_name>
namespace using dot notation.
Creating a package is quite straightforward, since it makes use of Example:
the operating system’s inherent hierarchical file structure. >>> from pkg import mod1
Consider the following arrangement: >>> mod1.m1()
First module

5 Attempt any TWO of the following 12


a) Write the output of the following 6M
i) >>> a=[2,5,1,3,6,9,7] (2m for each)
Here, there is a directory named pkg that contains two
>>> a[2:6]=[2,4,9,0]
modules, mod1.py and mod2.py. The contents of the modules
are: >>> print(a)
mod1.py Output: [2, 5, 2, 4, 9, 0, 7]
def m1():
print("first module") ii) >>> b=[“Hello”,”Good”]
>>> b.append(“python”)
mod2.py >>>print(b)
def m2(): Output: ['Hello', 'Good', 'python']
print("second module") iii) >>>t1=[3,5,6,7] output:
>>>print(t1[2]) >>>6
If the pkg directory resides in a location where it can be found, you >>>print(t1[-1]) >>>7
can refer to the two modules with dot >>>print(t1[2:]) >>>[6, 7]
notation(pkg.mod1, pkg.mod2) and import them with the >>>print(t1[:]) >>>[3, 5, 6, 7]
syntax: b) Explain method overloading in python with example 6M (3m for
Method overloading is the ability to define the method with explanation, 3m
Syntax-1
import <module_name>[, <module_name> ...]
the same name but with a different number of arguments for example)
Example: and data types.
>>>import pkg.mod1, pkg.mod2 With this ability one method can perform different tasks,
>>> pkg.mod1.m1() depending on the number of arguments or the types of the
first module arguments given.

Page 15 of 23 Page 16 of 23

Downloaded by Krushna Karmalkar (krushnakarmalkar00@gmail.com) Downloaded by Krushna Karmalkar (krushnakarmalkar00@gmail.com)


lOMoARcPSD|35683512 lOMoARcPSD|35683512

Method overloading is a concept in which a method in a class alternatives available in python that make it possible to call
performs operations according to the parameters passed to the same method but with different number of arguments.
it. c) Write a program to open a file in write mode and append 6M for any
As in other languages we can write a program having two some content at the end of file program with
methods with same name but with different number of file1 = open("myfile.txt", "w") suitable logic
arguments or order of arguments but in python if we will try L = ["This is Delhi \n", "This is Paris \n", "This is London"]
to do the same we will get the following issue with method file1.writelines(L)
overloading in Python: file1.close()
# to calculate area of rectangle
def area(length, breadth): # Append-adds at last
# append mode
calc = length * breadth
file1 = open("myfile.txt", "a")
print calc
#to calculate area of square # writing newline character
def area(size): file1.write("\n")
calc = size * size file1.write("Today")
print calc
area(3) # without newline character
area(4,5) file1.write("Tomorrow")
Output:
9 file1 = open("myfile.txt", "r")
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()
same name in a class in Python. file1.close()
This is because method arguments in python do not have a
type. A method accepting one argument can be called with Output:
an integer value, a string or a double as shown in next Output of Readlines after appending
example. This is Delhi
class Demo: This is Paris
def method(self, a): This is London
print(a) TodayTomorrow
obj= Demo()
obj.method(50) 6 Attempt any TWO of the following 12
obj.method('Meenakshi') a) Explain package Numpy with example 6M (3m for
obj.method(100.2) • NumPy is the fundamental package for scientific explanation and
Output: computing with Python. NumPy stands for 3m for example)
50 "Numerical Python". It provides a high-performance
Meenakshi multidimensional array object, and tools for working
100.2 with these arrays.
Same method works for three different data types. Thus, we • An array is a table of elements (usually numbers), all
cannot define two methods with the same name and same of the same type, indexed by a tuple of positive
number of arguments but having different type as shown in integers and represented by a single variable.
the above example. They will be treated as the same NumPy's array class is called ndarray. It is also known
method. by the alias array.
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 17 of 23 Page 18 of 23

Downloaded by Krushna Karmalkar (krushnakarmalkar00@gmail.com) Downloaded by Krushna Karmalkar (krushnakarmalkar00@gmail.com)


lOMoARcPSD|35683512 lOMoARcPSD|35683512

same type. Arrays can be made up of any number of >>> type(arr)


dimensions. <class 'numpy.ndarray'>
• In NumPy, dimensions are called axes. Each >>> print("No. of dimension: ", arr.ndim)
dimension of an array has a length which is the total No. of dimension: 2
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)
contained in an array in all the dimension. The size of >> >print("size of array: ", arr.size)
NumPy arrays are fixed; once created it cannot be size of array: 6
changed again. >>> print("Type of elements in array: ", arr.dtype)
• Numpy arrays are great alternatives to Python Lists. Type of elements in array: int32
Some of the key advantages of Numpy arrays are that >>> print("No of bytes:", arr.nbytes)
they are fast, easy to work with, and give users the No of bytes: 24
opportunity to perform calculations across entire b) Write a program to implement the concept of inheritance 6M for any
arrays. in python suitable
• A one dimensional array has one axis indicated by • In inheritance objects of one class procure the example of
Axis-0. That axis has five elements in it, so we say it properties of objects of another class. inheritance
has length of five. • Inheritance provide code usability, which means that
• A two dimensional array is made up of rows and some of the new features can be added to the code
columns. All rows are indicated by Axis-0 and all while using the existing code.
columns are indicated by Axis-1. If Axis-0 in two • The mechanism of designing or constructing classes
dimensional array has three elements, so its length it from other classes is called inheritance.
three and Axis-1 has six elements, so its length is six. • The new class is called derived class or child class and
the class from which this derived class has been
Execute Following command to install numpy in window, inherited is the base class or parent class.
Linux and MAC OS: • In inheritance, the child class acquires the properties
python -m pip install numpy and can access all the data members and functions
To use NumPy you need to import Numpy: defined in the parent class. A child class can also
import numpy as np # alias np provide its specific implementation to the functions
of the parent class.
Using NumPy, a developer can perform the following Syntax:
operations: class A:
1. Mathematical and logical operations on arrays. # properties of class A
2. Fourier transforms and routines for shape manipulation. class B(A):
3. Operations related to linear algebra. # class B inheriting property of class A
4. NumPy has in-built functions for linear algebra and # more properties of class B
random number generation
Example 1: Inheritance without using constructor.
Example: class Vehicle: #parent class
For NumPy with array object. name="Maruti"
>>> import numpy as np def display(self):
>>> a=np.array([1,2,3]) # one dimensional array print("Name= ",self.name)
>>> print(a) class Category(Vehicle): #derived class
[1 2 3] price=2000
>>> arr=np.array([[1,2,3],[4,5,6]]) # two dimensional array def disp_price(self):
>>> print(arr) print("Price=$",self.price)
[[1 2 3] car1=Category()
[4 5 6]] car1.display()

Page 19 of 23 Page 20 of 23

Downloaded by Krushna Karmalkar (krushnakarmalkar00@gmail.com) Downloaded by Krushna Karmalkar (krushnakarmalkar00@gmail.com)


lOMoARcPSD|35683512 lOMoARcPSD|35683512

car1.disp_price() • There can be one or more except blocks. Multiple


Output: except blocks with different exception names can be
Name= Maruti chained together.
Price=$ 2000 • The except blocks are evaluated from top to bottom
in the code, but only one except block is executed for
Example 2: Inheritance using constructor. each exception that is thrown.
class Vehicle: #parent class • The first except block that specifies the exact
def __init__(self,name): exception name of the thrown exception is executed.
self.name=name If no except block specifies a matching exception
def display(self): name then an except block that does not have an
print("Name= ",self.name) exception name is selected, if one is present in the
class Category(Vehicle): #derived class code.
def __init__(self,name,price): • For handling exception in Python, the exception
Vehicle.__init__(self,name) handler block needs to be written which consists of
# passing data to base class constructor set of statements that need to be executed according
self.price=price to raised exception. There are three blocks that are
def disp_price(self): used in the exception handling process, namely, try,
print("Price=$ ",self.price) except and finally.
car1=Category("Maruti",2000)
car1.display() 1. try Block: A set of statements that may cause error during
car1.disp_price() runtime are to be written in the try block.
car2=Category("BMW",5000) 2. except Block: It is written to display the execution details
car2.display() to the user when certain exception occurs in the program.
car2.disp_price() The except block executed only when a certain type as
Output: exception occurs in the execution of statements written in
Name= Maruti the try block.
Price=$ 2000 3. finally Block: This is the last block written while writing an
Name= BMW exception handler in the program which indicates the set of
Price=$ 5000 statements that many use to clean up to resources used by
c) Explain Try-except block used in exception handling in 6M (3m for the program.
python with example explanation and
• In Python, exceptions can be handled using a try 3m for program) Syntax:
statement. A try block consisting of one or more try:
statements is used by programmers to partition code D the operations here
that might be affected by an exception. ......................
• A critical operation which can raise exception is except Exception1:
placed inside the try clause and the code that handles If there is Exception1, then execute this block.
exception is written in except clause. except Exception2:
• The associated except blocks are used to handle any If there is Exception2, then execute this block.
resulting exceptions thrown in the try block. That is ......................
we want the try block to succeed and if it does not else:
succeed, we want to control to pass to the catch If there is no exception then execute this block.
block.
• If any statement within the try block throws an Example: For try-except clause/statement.
exception, control immediately shifts to the catch try:
block. If no exception is thrown in the try block, the fh = open("testfile", "w")
catch block is skipped. fh.write("This is my test file for exception handling!!")

Page 21 of 23 Page 22 of 23

Downloaded by Krushna Karmalkar (krushnakarmalkar00@gmail.com) Downloaded by Krushna Karmalkar (krushnakarmalkar00@gmail.com)


lOMoARcPSD|35683512

except IOError:
print ("Error: can\'t find file or read data")
else:
print ("Written content in the file successfully")
fh.close()

Page 23 of 23

Downloaded by Krushna Karmalkar (krushnakarmalkar00@gmail.com)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy