XXXXX: e Some Difference in The Candidate's Answers and Model Answer. Candidate's Understanding
XXXXX: e Some Difference in The Candidate's Answers and Model Answer. Candidate's Understanding
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________ __________________________________________________________________________________________________
Shift value is moved 1010 << 2
left by the =101000 = test()
number of bits 40 print("global variable=",g)
specified by the
right operand. output:
>> Binary Right The left operand's a>>2 = local variable= 20
Shift value is moved 1010 >> 2 Global variable= 10
right by the =0010 = 2 global variable= 10
number of bits
specified by the
right operand. d) Write python program to illustrate if else ladder. 4M
b) Write any four methods of dictionary. 4M
Ans i = 20 4M (for correct
Ans 4M (any four, if (i == 10): program and
1M each) print ("i is 10") logic)
elif (i == 15):
print ("i is 15")
elif (i == 20):
print ("i is 20")
else:
print ("i is not present")
output:
i is 20
c) What is local and global variables? Explain with appropriate example. 4M (Similar type of program can consider)
Ans Global variables: global variables can be accessed throughout the program 4M (2M for
3. Attempt any THREE of the following: 12 M
body by all functions. explanation
Local variables: local variables can be accessed only inside the function in and 2M for a) Write basis operations of list. 4M
which they are declared example)
Concept Diagram: Ans 1)Accessing values in list: Any two
Accessing elements liters from a list in Python is a method to get values that are stared operations:
in the list at a particular location or index.
To access values in lists, use the square brackets for slicing along with the index or 2 M for each
indices to obtain value available at that index.
Example: accessing list values.
>>> list1 = ["one","two",3,10,"six",20]
>>> list1[0]
'one'
>>> list1[-2]
A global variable (x) can be reached and modified anywhere in the code, local 'six'
variable (z) exists only in block 3. >>> list1[1:3]
Example: ['two', 3]
g=10 #global variable g >>> list1[3:]
def test(): [10, 'six', 20]
l=20 #local variable l >>> list1[:4]
print("local variable=",l) ['one', 'two', 3, 10]
# accessing global variable >>>
print("Global variable=",g)
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________ __________________________________________________________________________________________________
class Demo: except Exception1: Ans Python Command line arguments are input parameters passed to the script when 1 M for
def method(self, a): If there is Exception1, then execute this block. executing them. Almost all programming language provide support for command line definition and
print(a) except Exception2: arguments. Then we also have command line options to set some specific options for 3 M for
the program. program
obj= Demo() If there is Exception2, then execute this block.
obj.method(50) ...................... There are many options to read python command line arguments. The three most
obj.method('Meenakshi') else: common ones are:
obj.method(100.2) If there is no exception then execute this block. Python sys.argv
Output: Python getopt module
50 Example: For try-except clause/statement. Python argparse module
Meenakshi n=10
100.2 m=0 Program:
d) Explain how try-catch block is used for exception handling in python. 4M try: import sys
n/m x=int(sys.argv[1])
Ans • In Python, exceptions can be handled using a try statement. A try block Proper
except ZeroDivisionError: y=int(sys.argv[2])
consisting of one or more statements is used by programmers to partition code explanation
print("Divide by zero error") sum=x+y
that might be affected by an exception.
• A critical operation which can raise exception is placed inside the try clause and the 4 M else: print("The addition is :",sum)
code that handles exception is written in except clause. print (n/m)
• The associated except blocks are used to handle any resulting exceptions thrown in Output:
Output:
the try block. That is we want the try block to succeed and if it does not succeed, we Divide by zero error
want to control to pass to the catch block. C:\Python34\python sum.py 6 4
• If any statement within the try block throws an exception, control immediately shifts The addition is : 10
to the catch block. If no exception is thrown in the try block, the catch block is skipped. 4. Attempt any THREE of the following: 12 M c) Write python code to count frequency of each characters in a given file. 4M
• There can be one or more except blocks. Multiple except blocks with different
a) Compare list and dictionary. (Any 4 points) 4M Ans import collections Any proper
exception names can be chained together.
import pprint logic program
• The except blocks are evaluated from top to bottom in the code, but only one except Ans List Dictionary Any four point, 4M
block is executed for each exception that is thrown. file_input = input('File Name: ')
• The first except block that specifies the exact exception name of the thrown exception List is a collection of index values pairs Dictionary is a hashed structure of 1 M for 1 point with open(file_input, 'r') as info:
is executed. If no except block specifies a matching exception name then an except as that of array in c++. key and value pairs. count = collections.Counter(info.read().upper())
block that does not have an exception name is selected, if one is present in the code. value = pprint.pformat(count)
List is created by placing elements in [ ] Dictionary is created by placing
• For handling exception in Python, the exception handler block needs to be written print(value)
separated by commas “, “ elements in { } as “key”:”value”,
which consists of set of statements that need to be executed according to raised d) Write python program to read contents of abc.txt and write same content to 4M
each key value pair is separated by
exception. There are three blocks that are used in the exception handling process, pqr.txt.
commas “, “
namely, try, except and finally.
1. try Block: A set of statements that may cause error during runtime are to be written The indices of list are integers starting The keys of dictionary can be of any Ans with open('abs.txt','r') as firstfile, open('prq.txt','w') as secondfile: Any proper
in the try from 0. data type. # read content from first file logic program
block. for line in firstfile: for 4 M
2. except Block: It is written to display the execution details to the user when certain The elements are accessed via indices. The elements are accessed via key- # write content to second file
exception occurs in the program. The except block executed only when a certain type as values. secondfile.write(line)
exception occurs in the execution of statements written in the try block. The order of the elements entered are There is no guarantee for
maintained. maintaining order.
5. Attempt any TWO of the following: 12 M
Syntax:
try: b) What is command line argument? Write python code to add b) two 4M
a) Write different data types in python with suitable example. 6M
D the operations here numbers given as input from command line arguments and print its sum.
...................... Ans Data types in Python programming includes:
Numbers: Represents numeric data to perform mathematical operations.
Page No: 10 | 21 Page No: 11 | 21 Page No: 12 | 21
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________ __________________________________________________________________________________________________
String: Represents text characters, special symbols or alphanumeric data. 5. String Data Type: String is a collection of group of characters. Strings are identified 8. Dictionary: Dictionary is an unordered collection of key-value pairs. It is the same as
List: Represents sequential data that the programmer wishes to sort, merge etc. as a contiguous set of characters enclosed in single quotes (' ') or double quotes (" "). the hash table type. The order of elements in a dictionary is undefined, but we can
6m for data
Tuple: Represents sequential data with a little difference from list. types
Any letter, a number or a symbol could be a part of the string. Strings are iterate over the following:
Dictionary: Represents a collection of data that associate a unique key with each unchangeable (immutable). Once a string is created, it cannot be modified. o The key
value. Example: For string data type. o The value
Boolean: Represents truth-values (true or false). >>> s1="Hello" #string in double quotes o The items (key-value pairs) in a dictionary.
>>> s2='Hi' #string in single quotes When we have the large amount of data, the dictionary data type is used. Items in
1. Integers (int Data Type): An integer is a whole number that can be positive (+) or >>> s3="Don't open the door" #single quote string in double quotes dictionaries are enclosed in curly braces { } and separated by the comma (,). A colon (:)
negative (−). Integers can be of any length, it is only limited by the memory available. >>> s4='I said "yipee"' #double quote string in single quotes is used to separate key from value. Values can be assigned and accessed using square
Example: For number data types are integers. >>>type(s1) braces ([]).
>>>a=10 <class 'str'> Example: For dictionary data type.
>>>b -10 >>> dic1={1:"First","Second":2}
To determine the type of a variable type() function is used. 6. List Data Type: List is an ordered sequence of items. It is one of the most used >>> dic1
>>>type(a) datatype in Python and is very flexible. {1: 'First', 'Second': 2}
>>> <class 'int'> List can contain heterogeneous values such as integers, floats, strings, tuples, lists and >>> type(dic1)
dictionaries but they are commonly used to store collections of homogeneous objects. <class 'dict'>
2. Boolean (Bool Data Type: The simplest build-in type in Python is the bool type, it The list datatype in Python programming is just like an array that can store a group of >>> dic1[3]="Third"
represents the truth-values False and True. Internally the true value is represented as elements and we can refer to these elements using a single name. Declaring a list is >>> dic1
1 and false is 0. pretty straight forward. Items separated by commas ( , ) are enclosed within brackets [ {1: 'First', 'Second': 2, 3: 'Third'}
For example ]. >>> dic1.keys()
>>>a = 18 > 5 Example: For list. dict_keys([1, 'Second', 3])
>>>print(a) >>> first=[10, 20, 30] # homogenous values in list >>> dic1.values()
True >>> second=["One","Two","Three"] # homogenous values in list dict_values(['First', 2, 'Third'])
b=2>3 >>> first >>>
print(b) [10, 20, 30]
>>> second b) Example module. How to define module. 6M
False
['One', 'Two', 'Three'] Ans A module allows you to logically organize your Python code. Grouping related code 2 M for
3. Floating-Point/Float Numbers (Float Data Type): Floating-point number or Float is >>> first + second # prints the concatenated lists into a module makes the code easier to understand and use. A module is a Python module
a positive or negative number with a fractional part. A floating point number is [10, 20, 30, 'One', 'Two', 'Three'] object with arbitrarily named attributes that you can bind and reference. explanation
accurate up to 15 decimal places. Integer and floating points are separated by decimal
points. 1 is integer, 1.0 is floating point number. 7. Tuple Data Type: Tuple is an ordered sequence of items same as list. The only Simply, a module is a file consisting of Python code. A module can define functions,
difference is that tuples are immutable. classes and variables. A module can also include runnable code.
Example: Floating point number.
x=10.1 Tuples once created cannot be modified. It is defined within parentheses ( ) where Example
type(x) items are separated by commas ( , ).
<class 'float'> A tuple data type in python programming is similar to a list data type, which also The Python code for a module named aname normally resides in a file named
contains heterogeneous items/elements. aname.py. Here's an example of a simple module, support.py 2 M for
Example: For tuple. creating
4. Complex Numbers (Complex Data Type): Complex numbers are written in the form, def print_func( par ): module
x + yj, where x is the real part and y is the imaginary part. >>> a=(10,'abc',1+3j)
print "Hello : ", par
Example: >>> a
return
Complex number. (10, 'abc', (1+3j))
To create a module just save the code you want in a file with the file extension .py:
>>>x = 3+4j >>> a[0] Example
>>>print(x.real) 10 Save this code in a file named mymodule.py
3.0 >>> a[0]=20 def greeting(name):
>>>print(x.imag) Traceback (most recent call last): print("Hello, " + name)
4.0 File "<pyshell#12>", line 1, in <module>
Now we can use the module we just created, by using the import statement: 2 M for
accessing/using
Page No: 13 | 21 Page No: 14 | 21 Page No: 15 | 21
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________ __________________________________________________________________________________________________
Example module Example:
*If students have attempted by using “Tuple” then
Import the module named mymodule, and call the greeting function: # int
num1 = 10
import mymodule
#To create tuple num2 = 100
mymodule.greeting("ABC")
c) Write python program to perform following operations on Set (Instead of 6M tuple1=(10,20,30,40,50)
print (tuple1) # float
Tuple)
#Access tuple values a = 10.5
i) Create set print (tuple1[1]) b = 8.9
ii) Access set Element print (tuple1[0:3])
# complex numbers
iii) Update set # deleting tuple
x = 3 + 4j
iv) Delete set del tuple1
y = 9 + 8j
print (tuple1)
Ans # To Create set
2. String
S={10,20,30,40,50} output:
6m for any
suitable (10, 20, 30, 40, 50) A string is usually a bit of text (sequence of characters). In Python we use ” (double
# To Access Elements from set
program 20 quotes) or ‘ (single quotes) to represent a string.
print (S) (10, 20, 30)
There are several ways to create strings in Python:
Traceback (most recent call last):
#To add element into set using add method
S.add(60) (If students
File "C:\Users\Vijay Patil\AppData\Local\Programs\Python\Python310\temp.py", line 1. We can use ‘ (single quotes), see the string str in the following code.
9, in <module>
print(S) attempted with 2. We can use ” (double quotes), see the string str2 in the source code below.
“set” give print (tuple1)
#To update set using update method marks as per NameError: name 'tuple1' is not defined. Did you mean: 'tuple'? 3. Triple double quotes “”” and triple single quotes ”’ are used for creating multi-line
S.update(['A','B']) marking strings in Python.
print(S) scheme)
Example:
#To Delete element from Set using discard() method OR
str = 'beginnersbook'
S.discard(30) (If students str2 = "Chaitanya"
print(S) 6. Attempt any TWO of the following: 12 M
attempted with # multi-line string
“Tuple” a) Explain mutable and immutable data structures. 6M str3 = """Welcome to
#To delete element from set using remove() method Pythonsbook"""
S.remove('A') Then Ans The data types in Python are divided in two categories: 3m for mutable
print(S) Immutable data types – Values cannot be changed. Immutable data types in Python are data structure str4 = '''This is a tech
2M-create
1. Numbers and 3m for paper'''
#To delete element from set using pop() method Tuple
2. String immutable data
S.pop() 2M-Access 3. Tuple structure
print(S) tuple Mutable data types – Values can be changed. Mutable data types in Python are: 3. Tuple
1. List
2M-delete In Python, a tuple is similar to List except that the objects in tuple are immutable which
output: 2. Dictionaries
Tuple) means we cannot change the elements of a tuple once assigned. On the other hand, we
{50, 20, 40, 10, 30} 3. Sets
can change the elements of a list.
{50, 20, 40, 10, 60, 30}
{'B', 50, 20, 'A', 40, 10, 60, 30} 1. Numbers To create a tuple in Python, place all the elements in a () parenthesis, separated by
{'B', 50, 20, 'A', 40, 10, 60} Python supports integers, floats and complex numbers. commas. A tuple can have heterogeneous data items, a tuple can have string and list as
{'B', 50, 20, 40, 10, 60} An integer is a number without decimal point for example 5, 6, 10 etc. data items as well.
{50, 20, 40, 10, 60} A float is a number with decimal point for example 6.7, 6.0, 10.99 etc. Example
A complex number has a real and imaginary part for example 7+8j, 8+11j etc. # tuple of strings
(Any other suitable example can consider) my_data = ("hi", "hello", "bye")
Page No: 16 | 21 Page No: 17 | 21 Page No: 18 | 21
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________ __________________________________________________________________________________________________
Create suitable method for reading and printing students details.
# tuple of int, float, string # function feed
my_data2 = (1, 2.8, "Hello World") Ans class Student: 2 M for class def feed(self):
definition print("I eat only plants. I am vegetarian.")
def getStudentDetails(self):
# tuple of string and list
my_data3 = ("Book", [1, 2, 3]) self.rollno=input("Enter Roll Number : ") herbi = Herbivorous()
SUMMER-2022 EXAMINATION The List has the variable The tuple has the fixed length f) How to give single and multiline comment in Python 2M (1m each)
Subject Name: Programming with Python Model Answer Subject Code: 22616 length Single line comment: Single-line comments are created simply by
List operations are more error Tuples operations are safe beginning a line with the hash (#) character, and they are
Important Instructions to examiners: prone. automatically terminated by the end of line.
1. The answers should be examined by key words and not as word-to-word as given in Lists can be used to store Tuples are used to store only Example:
homogeneous and heterogeneous elements. # print is a statement
the model answer scheme.
heterogeneous elements. print(‘Hello Python’)
2. The model answer and the answer written by candidate may vary but the examiner
List is useful for insertion and Tuple is useful for readonly
may try to assess the understanding level of the candidate. Multi line comment: Python multi-line comment is a piece of text
deletion operations. operations like accessing
3. The language errors such as grammatical, spelling errors should not be given more elements. enclosed in a delimiter (""") Triple quotation marks.
Importance (Not applicable for subject English and Communication Skills. List iteration is slower and is Tuple iteration is faster. Example:
4. While assessing figures, examiner may give credit for principal components time consuming. """ Multi-line comment used
indicated in the figure. The figures drawn by candidate and model answer may vary. d) Explain Local and Global variable 2M (1m each) print("Python Comments") """
The examiner may give credit for any equivalent figure drawn. Local Variables: Local variables are those which are initialized or
5. Credits may be given step wise for numerical problems. In some cases, the assumed inside a function and belongs only to that particular function. It To add a multiline comment you could insert a # for each line:
constant values may vary and there may be some difference in the candidate’s cannot be accessed anywhere outside the function Example:
answers and model answer. Example: #This is a comment
def f(): #written in
6. In case of some questions credit may be given by judgement on part of examiner of
# local variable #more than just one line
relevant answer based on candidate’s understanding. s = "I love Python Programming" print("Hello, World!")
7. For programming language papers, credit may be given to any other program based print(s)
g) List different modes of opening file in Python 2M
on equivalent concept. # Driver code
f() Modes for opening file: (Any 2 names 2M)
8. As per the policy decision of Maharashtra State Government, teaching in • r: open an existing file for a read operation.
Output
English/Marathi and Bilingual (English + Marathi) medium is introduced at first year I love Python Programming • w: open an existing file for a write operation. If the file
of AICTE diploma Programme from academic year 2021-2022. Hence if the students already contains some data then it will be overridden.
in first year (first and second semesters) write answers in Marathi or bilingual Global Variables: The global variables are those which are defined
outside any function and which are accessible throughout the • a: open an existing file for append operation. It won’t
language (English +Marathi), the Examiner shall consider the same and assess the
program i.e. inside and outside of every function. override existing data.
answer based on matching of concepts with model answer.
Example: • r+: To read and write data into the file. The previous
# This function uses global variable s data in the file will be overridden.
Q. Sub Answer Marking Scheme
No. Q. N.
def f(): • w+: To write and read data. It will override existing data.
1 Attempt Any FIVE of the following 10
print("Inside Function", s) • a+: To append and read data from the file. It won’t
a) Name different modes of Python 2M (1m each) override existing data.
# Global scope
Python has two basic modes:
s = "I love Python Programming"
• Script (Normal Mode) 2 Attempt any THREE of the following 12
f()
• Interactive Mode print("Outside Function", s)
a) Write a program to print following 4M (for correct
b) List identity operators in python 2M (1m each) 1 program and
Identity operators in Python are 12 logic)
Output:
• is 123
Inside Function I love Python Programming
• is not 1234
Outside Function I love Python Programming
c) Give two differences between list and tuple 2M (1m for each e) Define class and object in python 2M (Any suitable
difference, any 2 for i in range(1,5):
List Tuple Class: A class is a user-defined blueprint or prototype from which definition: 1M
difference) for j in range(1,i+1):
Lists are mutable Tuples are immutable objects are created. Classes provide a means of bundling data Each)
print(j,end=' ')
Lists consume more memory Tuple consume less memory and functionality together.
print()
as compared to the list
b) Explain four Buit-in tuple functions in python with example 4M ( 1M for each
Lists have several built-in Tuple does not have many Object: An object is an instance of a class that has some
function with
methods built-in methods. attributes and behavior. Objects can be used to access the
example)
The unexpected changes and In tuple, it is hard to take attributes of the class.
errors are more likely to occur place.
>>> s1="Hello" #string in double quotes 8. Dictionary: Dictionary is an unordered collection of key- it item is in list or in >>> print("Hello"
>>> s2='Hi' #string in single quotes value pairs. It is the same as the hash table type. The order sequence. not in x)
>>> s3="Don't open the door" #single quote string in double of elements in a dictionary is undefined, but we can iterate False
quotes over the following:
>>> s4='I said "yipee"' #double quote string in single quotes o The key Assignment Operators (Augmented Assignment Operators):
Assignment operators are used in Python programming to assign
>>>type(s1) o The value
values to variables. The assignment operator is used to store the
<class 'str'> o The items (key-value pairs) in a dictionary.
value on the right-hand side of the expression on the left-hand side
When we have the large amount of data, the dictionary data variable in the expression.
6. List Data Type: List is an ordered sequence of items. It is type is used. Items in dictionaries are enclosed in curly braces For example, a = 5 is a simple assignment operator that assigns the
one of the most used datatype in Python and is very flexible. { } and separated by the comma (,). A colon (:) is used to value 5 on the right to the variable a on the left.
List can contain heterogeneous values such as integers, separate key from value. Values can be assigned and There are various compound operators in Python like a += 5 that
floats, strings, tuples, lists and dictionaries but they are accessed using square braces ([]). adds to the variable and later assigns the same. It is equivalent to
commonly used to store collections of homogeneous Example: For dictionary data type. a = a + 5.
objects. The list datatype in Python programming is just like >>> dic1={1:"First","Second":2} Following table shows assignment operators in Python
an array that can store a group of elements and we can refer >>> dic1 programming:
to these elements using a single name. Declaring a list is {1: 'First', 'Second': 2} Sr. Operator Description Example
pretty straight forward. Items separated by commas ( , ) are >>> type(dic1) No.
enclosed within brackets [ ]. <class 'dict'> 1 = Assigns values from right c=a+b
Example: For list. >>> dic1[3]="Third" side operands to assigns value
>>> first=[10, 20, 30] # homogenous values in list >>> dic1 of a + b
left side operand.
>>> second=["One","Two","Three"] # homogenous values in {1: 'First', 'Second': 2, 3: 'Third'}
into c
list >>> dic1.keys()
>>> first dict_keys([1, 'Second', 3]) 2 += It adds right operand to c += a is
[10, 20, 30] >>> dic1.values() the left operand and equivalent to
>>> second dict_values(['First', 2, 'Third']) assign the result to left c=c+a
['One', 'Two', 'Three'] >>> operand.
>>> first + second # prints the concatenated lists b) Explain membership and assignment operators with 4M: 2m for
[10, 20, 30, 'One', 'Two', 'Three'] example membership 3 −= It subtracts right operand c −= a is
Membership Operators: The membership operators in Python are operators and from the left equivalent to
7. Tuple Data Type: Tuple is an ordered sequence of items used to find the existence of a particular element in the sequence, 2m for operand and assign the c=c−a
same as list. The only difference is that tuples are immutable. and used only with sequences like string, tuple, list, dictionary etc. assignment result to left operand.
Tuples once created cannot be modified. It is defined within Membership operators are used to check an item or an element operators
that is part of a string, a list or a tuple. A membership operator 4 *= It multiplies right operand operand and
parentheses ( ) where items are separated by commas ( , ).
reduces the effort of searching an element in the list. Python with the left assign the
A tuple data type in python programming is similar to a list
provides ‘in’ and ‘not in’ operators which are called membership result to left
data type, which also contains heterogeneous operand and assign the operand.
operators and used to test whether a value or variable is in a
items/elements. result to left operand.
sequence.
Example: For tuple. c *= a is
Sr. Operator Description Example equivalent to
>>> a=(10,'abc',1+3j) No
>>> a c=c*a
(10, 'abc', (1+3j)) 1 in True if value is >>> x="Hello
found in list or in World" 5 /= It divides left operand c /= a is
>>> a[0]
sequence, and false >>> print('H' in x) with the right operand equivalent to
10
it item is not in list True and assign the result to
>>> a[0]=20 or in sequence left operand. c=c/a
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module> 2 not in True if value is not >>> x="Hello 6 %= It takes modulus using c %= a is
found in list or in World" two operands and assign equivalent to
sequence, and false the result to left operand.
c) Explain use of format() method with example 4M (2m for use special meaning to the return,finally,import,def
if-elif-else (ladder) statements: Here, a user can decide among The format() method formats the specified value(s) and insert and 2m for language
multiple options. The if statements are executed from the top them inside the string's placeholder. example) compiler/interpreter
down. As soon as one of the conditions controlling the if is true, The placeholder is defined using curly brackets: {}. Identifiers: names given to def square,num=20,
the statement associated with that if is executed, and the rest of The format() method returns the formatted string. different parts of program a_lst=[1,2,3];
the ladder is bypassed. If none of the conditions is true, then the Syntax like variables, functions, here square,num and a_lst are
final else statement will be executed. string.format(value1, value2...) object, class, names given to identifiers.
Syntax: different datatypes.
if (condition-1): Example: Literals/Constants: Data String: ‘Mayank‘,’abc‘,’anish‘;
statement #named indexes: items that have fixed values Numeric: 1,1.2,4,-3.95;
elif (condition-2): >>>txt1 = ("My name is {fname}, I'm {age}".format(fname = Boolean: True,False
statements "abc", age = 36)) Special literal None; meaning nothing
. >>>print(txt1) e) Write a program illustrating use of user defined package in 4M (2m for
. My name is abc, I'm 36 python defining
elif(condition-n): A package is a hierarchical file directory structure that defines a package and 2m
statements #numbered indexes: single Python application environment that consists of modules
>>>txt2 =( "My name is {0}, I'm {1}".format("xyz",36))
for import
else: and subpackages and sub-subpackages, and so on.
statements >>>print(txt2) package in
Packages allow for a hierarchical structuring of the module program)
My name is xyz, I'm 36 namespace using dot notation.
Example: Creating a package is quite straightforward, since it makes use of
Example: #empty placeholders: the operating system’s inherent hierarchical file structure.
i = 20 >>>txt3 = ("My name is {}, I'm {}".format("pqr",36)) Consider the following arrangement:
if (i == 10): >>>print(txt3)
print ("i is 10") My name is pqr, I'm 36
elif (i == 15): d) Explain building blocks of python 4M
print ("i is 15") Character set: All characters that python can recognize. The
elif (i == 20): below table illustrates the Python character set along with
print ("i is 20") examples. Here, there is a directory named pkg that contains two
else: character Set Examples modules, mod1.py and mod2.py. The contents of the modules
print ("i is not present") Letters: Upper case and A-Z,a-z are:
lower case english mod1.py
output: alphabets def m1():
i is 20 Digits: all digits 0-9 print("first module")
Special symbols space,+,-,**,*,%,//,/,==,!=,>,<
Concept Diagram: Whitespaces Blank space,tabs mod2.py
Other unicode characters All ASCII and Unicode characters def m2():
Tokens: Tokens in python are building blocks of the Python print("second module")
programming language. The role letters and words play for the
English language, Similar to role token play for a python If the pkg directory resides in a location where it can be found, you
programming language. can refer to the two modules with dot
Python has the following tokens: notation(pkg.mod1, pkg.mod2) and import them with the
1)keywords syntax:
2)identifiers
3)literals Syntax-1
a)String literals import <module_name>[, <module_name> ...]
b)Numeric literals Example:
c)Boolean Literals >>>import pkg.mod1, pkg.mod2
d)Special literal None >>> pkg.mod1.m1()
Tokens Example first module
Keywords: Words that are False,True,if,elif,else,for,
already defined and convey a while,pass,continue,lambda,
same type. Arrays can be made up of any number of >>> type(arr) car1.disp_price()
dimensions. <class 'numpy.ndarray'> Output:
• In NumPy, dimensions are called axes. Each >>> print("No. of dimension: ", arr.ndim) Name= Maruti
dimension of an array has a length which is the total No. of dimension: 2 Price=$ 2000
number of elements in that direction. >>> print("Shape of array: ", arr.shape)
• The size of an array is the total number of elements Shape of array: (2, 3) Example 2: Inheritance using constructor.
contained in an array in all the dimension. The size of >> >print("size of array: ", arr.size) class Vehicle: #parent class
NumPy arrays are fixed; once created it cannot be size of array: 6 def __init__(self,name):
changed again. >>> print("Type of elements in array: ", arr.dtype) self.name=name
• Numpy arrays are great alternatives to Python Lists. Type of elements in array: int32 def display(self):
Some of the key advantages of Numpy arrays are that >>> print("No of bytes:", arr.nbytes) print("Name= ",self.name)
they are fast, easy to work with, and give users the No of bytes: 24 class Category(Vehicle): #derived class
opportunity to perform calculations across entire b) Write a program to implement the concept of inheritance 6M for any def __init__(self,name,price):
arrays. in python suitable Vehicle.__init__(self,name)
• A one dimensional array has one axis indicated by • In inheritance objects of one class procure the example of # passing data to base class constructor
Axis-0. That axis has five elements in it, so we say it properties of objects of another class. inheritance self.price=price
has length of five. • Inheritance provide code usability, which means that def disp_price(self):
• A two dimensional array is made up of rows and some of the new features can be added to the code print("Price=$ ",self.price)
columns. All rows are indicated by Axis-0 and all while using the existing code. car1=Category("Maruti",2000)
columns are indicated by Axis-1. If Axis-0 in two • The mechanism of designing or constructing classes car1.display()
dimensional array has three elements, so its length it from other classes is called inheritance. car1.disp_price()
three and Axis-1 has six elements, so its length is six. • The new class is called derived class or child class and car2=Category("BMW",5000)
the class from which this derived class has been car2.display()
Execute Following command to install numpy in window, inherited is the base class or parent class. car2.disp_price()
Linux and MAC OS: • In inheritance, the child class acquires the properties Output:
python -m pip install numpy and can access all the data members and functions Name= Maruti
To use NumPy you need to import Numpy: defined in the parent class. A child class can also Price=$ 2000
import numpy as np # alias np provide its specific implementation to the functions Name= BMW
of the parent class. Price=$ 5000
Using NumPy, a developer can perform the following Syntax: c) Explain Try-except block used in exception handling in 6M (3m for
operations: class A: python with example explanation and
1. Mathematical and logical operations on arrays. # properties of class A • In Python, exceptions can be handled using a try 3m for program)
2. Fourier transforms and routines for shape manipulation. class B(A): statement. A try block consisting of one or more
3. Operations related to linear algebra. # class B inheriting property of class A statements is used by programmers to partition code
4. NumPy has in-built functions for linear algebra and # more properties of class B that might be affected by an exception.
random number generation • A critical operation which can raise exception is
Example 1: Inheritance without using constructor. placed inside the try clause and the code that handles
Example: class Vehicle: #parent class exception is written in except clause.
For NumPy with array object. name="Maruti" • The associated except blocks are used to handle any
>>> import numpy as np def display(self): resulting exceptions thrown in the try block. That is
>>> a=np.array([1,2,3]) # one dimensional array print("Name= ",self.name) we want the try block to succeed and if it does not
>>> print(a) class Category(Vehicle): #derived class succeed, we want to control to pass to the catch
[1 2 3] price=2000 block.
>>> arr=np.array([[1,2,3],[4,5,6]]) # two dimensional array def disp_price(self): • If any statement within the try block throws an
>>> print(arr) print("Price=$",self.price) exception, control immediately shifts to the catch
[[1 2 3] car1=Category() block. If no exception is thrown in the try block, the
[4 5 6]] car1.display() catch block is skipped.
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________ __________________________________________________________________________________________________
Software Development Namespaces prevent conflicts between classes, methods and objects with the 3. insert() Method: We can insert one single item at a desired location by using the method
Web Applications same name that might have been written by different people. insert() or insert multiple items by squeezing it into an empty slice of a list.
b) Write the use of elif keyword in python. 2M A namespace is a system to have a unique name for each and every object in Example: Program for insert() method.
>>> list1=[10, 20]
Python. An object might be a variable or a method. Python itself maintains a
>>>list1
Ans elif' stands for 'else if' and is used in Python programming to test multiple conditions. Correct namespace in the form of a Python dictionary. [10,20]
The if statements are executed from the top down. As soon as one of the conditions controlling explanation 2 A namespace in python is a collection of names. So, a namespace is essentially >>> list1.insert(1,30)
the if is true, the statement associated with that if is executed, and the rest of the ladder is M a mapping of names to corresponding objects. >>> list1
bypassed. If none of the conditions is true, then the final else statement will be executed.
f) State the use of read() and readline () functions in python file handling. 2M [10, 30, 20]
c) Describe the Role of indentation in python. 2M Ans 1. read([n]) Method: read() 1 M and
The read method reads the entire contents of a file and returns it as a string, if number readline() 2. Attempt any THREE of the following: 12 M
Ans Indentation refers to the spaces at the beginning of a code line. Correct Role 2 of bytes are not given in the argument. If we execute read(3), we will get back the first
1M a) Explain membership and identity operators in Python. 4M
Generally, four whitespaces are used for indentation and is preferred over tabs. M three characters of the file.
Where in other programming languages the indentation in code is for readability only, Example: for read( ) method. Ans Membership Operators: Membership
(example is not
the indentation in Python is very important. f=open("sample.txt","r") The membership operators in Python are used to find the existence of a particular operator 2 M
mandatory)
Indentation helps to convey a better structure of a program to the readers. It is used to print(f.read(5)) # read first 5 data element in the sequence, and used only with sequences like string, tuple, list, and Identity
clarify the link between control flow constructs such as conditions or loops, and code print(f.read()) # read rest of the file dictionary etc.
contained within and outside of them. operator 2 M
Membership operators are used to check an item or an element that is part of a string,
Python uses indentation to indicate a block of code. 2. readline([n]) Method: a list or a tuple. A membership operator reduces the effort of searching an element in
Example: The readline() method just output the entire line whereas readline(n) outputs at most the list.
if 5 > 2: n bytes of a single line of a file. It does not read more than one line. Once, the end of Python provides ‘in’ and ‘not in’ operators which are called membership operators
print("Five is greater than two!") file is reached, we get empty string on further reading. and used to test whether a value or variable is in a sequence.
d) Define Data Hiding concept? Write two advantages of Data Hiding. 2M Example: For readline ( ) method. Operator Description Example
f=open("sample.txt","r")
Ans Data hiding is a concept which underlines the hiding of data or information from the Any relevant print(f.readline()) # read first line followed by\n in True if value is found in list or in >>> x="Hello World"
user. Definition 1 M, print(f.readline(3)) sequence, and false it item is not >>> print('H' in x)
Data hiding is a software development technique specifically used in Object-Oriented print(f.readline()) in list or in sequence True
any two
Programming (OOP) to hide internal object details (data members). g) Explain two ways to add objects / elements to list. 2M not in True if value is not found in list >>> x="Hello World"
Data hiding includes a process of combining the data and functions into a single unit Advantages 1
or in sequence, and false it item is >>> print("Hello" not in x)
to conceal data within a class by restricting direct access to the data from outside the M in list or in sequence. False
class. Ans 1)append method: The append() method adds an element to the end of a list. We can insert 1 Method for 1
a single item in the list data time with the append(). M (any two
Example: For append() method. Identity Operators: Sometimes, in Python programming a need to compare the
Advantages of Data Hiding methods) memory address of two objects; this is made possible with the help of the identity
>>> list1=[10,20,30]
Data hiding ensures exclusive data access to class members and protects object operator. Identity operators are used to check whether both operands are same or not.
>>> list1
integrity by preventing unintended or intended changes.
[10, 20, 30] Python provides ‘is’ and ‘is not’ operators which are called identity operators and both
Data hiding is also known as information hiding. An object's attributes may or may >>> list1.append(40) # add element at the end of list
not be visible outside the class definition.
are used to check if two values are located on the same part of the memory. Two
>>> list1 (example is not
Data hiding also minimizes system complexity for increase robustness by limiting variables that are equal does not imply that they are identical.
[10, 20, 30, 40] mandatory) Operator Description Example
interdependencies between software requirements.
The objects within the class are disconnected from irrelevant data.
It heightens the security against hackers that are unable to access confidential data. is Return true, if the variables on either side >>> a=3
2. extend() Method: The extend() method extends a list by appending items. We can add of the operator point to the same object >>> b=3
It helps to prevent damage to volatile data by hiding it from the public. several items using extend() method. and false otherwise. >>> print(a is b)
A user outside from the organization cannot attain the access to the data. Example: Program for extend() method. True
Within the organization/ system only specific users get the access. This allows better >>>list1=[10, 20, 30, 40] is not Return false, if the variables on either >>> a=3
operation. >>>list1 side of the operator point to the same >>> b=3
e) State use of namespace in python. 2M [10, 20, 30, 40] object and true otherwise. >>> print(a is not b)
>>> list1.extend([60,70]) #add elements at the end of list False
Ans Namespaces bring you three advantages: they group names into logical Correct/relevant >>> list1
use 2 M [10, 20, 30, 40, 60, 70] b) Write python program to display output like. 4M
containers, they prevent clashes between duplicate names, and third, they
provide context to names.
Page No: 2 | 20 Page No: 3 | 20 Page No: 4 | 20
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________ __________________________________________________________________________________________________
2 >>> list1.pop(2) Ans Like, C, C++, and Java, a file in Python programming can be opened in various modes Listing of
4 6 8 7 depending upon the purpose. For that, the programmer needs to specify the mode modes- 1 M
10 12 14 16 18 10 list.remove(item) It deletes the given item >>> list1 whether read 'r', write 'w', or append 'a' mode. Apart from this, two other modes exist, and explain ant
Ans a=2 Correct or any from the list. [1, 2, 3, 4, 5] which specify to open the file in text mode or binary mode. 2- 3 M
for i in range(1,5): relevant Logic/ >>> list1.remove(3) 1. The text mode returns strings while reading from the file. The default is reading in
for j in range(i): any other >>> list1
text mode.
print(a,end="\t") suitable [1, 2, 4, 5]
a+=2 2. The binary mode returns bytes and this is the mode to be used when dealing with
Program 4 M 11 list.reverse() It reverses the position >>> list1
print() (index number) of the items [1, 2, 3, 4, 5] non-text files like image or executable files.
in the list. >>> list1.reverse() The text and binary modes are used in conjunction with the r, w, and a modes. The list
c) Explain four built-in list functions. 4M >>> list1 of all the modes used in Python are given in following table:
[5, 4, 3, 2, 1] Sr. No. Mode Description
Ans Sr. No. Function Description Example 12 list.sort([func]) It sorts the elements inside >>> list1
1 len(list) It returns the length of the >>> list1 the list and uses compare [1, 3, 2, 5, 4] 1 r Opens a file for reading only. The file pointer is placed
Any 4 functions function if provided. >>> list1.sort() at the beginning of the file. This is the default mode.
list. [1, 2, 3, 4, 5]
>>> len(list1) 4 M, 1 M each >>> list1
5 [1, 2, 3, 4, 5] 2 rb Opens a file for reading only in binary format. The file
2 max(list) It returns the item that has >>> list1 d) Write python program using module, show how to write and use module by 4M pointer is placed at the beginning of the file. This is the
the maximum value in a [1, 2, 3, 4, 5] importing it. default mode.
list. >>> max(list1)
5 Ans For creating a module write following code and save it as p1.py Write module 2
#p1.py M and Import 2 3 r+ Opens a file for both reading and writing. The file
3 sum(list) Calculates sum of all the >>>list1
elements of list. [1, 2, 3, 4, 5] def add(a, b): M pointer placed at the beginning of the file.
>>>sum(list1) "This function adds two numbers and return the result"
15 result = a + b 4 rb+ Opens a file for both reading and writing in binary
4 min(list) It returns the item that has >>> list1 return result format. The file pointer placed at the beginning of the
the minimum value in a list. [1, 2, 3, 4, 5] file.
>>> min(list1)
def sub(a, b):
1 5 w Opens a file for writing only. Overwrites the file if the
"This function subtract two numbers and return the result"
5 list(seq) It converts a tuple into a >>> list1
list. [1, 2, 3, 4, 5] result = a – b file exists. If the file does not exist, creates a new file
>>> list(list1) return result for writing.
[1, 2, 3, 4, 5]
6 list.append(item) It adds the item to the end >>> list1 Import the definitions inside a module: 6 wb Opens a file for writing only in binary format.
of the list. [1, 2, 3, 4, 5] Overwrites the file if the file exists. If the file does not
>>> list1.append(6) import p1 exist, creates a new file for writing.
>>> list1 print(p1.add(10,20))
[1, 2, 3, 4, 5, 6] print(p1.sub(20,10)) 7 w+ Opens a file for both writing and reading. Overwrites
7 list.count(item) It returns number of times >>> list1
the item occurs in the list. [1, 2, 3, 4, 5, 6, 3] the existing file if the file exists. If the file does not
>>> list1.count(3)
Output: exist, creates a new file for reading and writing.
2 30
8 list.extend(seq) It adds the elements of the >>> list1 10 8 wb+ Opens a file for both writing and reading in binary
sequence at the end of the [1, 2, 3, 4, 5] format. Overwrites the existing file if the file exists. If
list. >>> list2
['A', 'B', 'C']
the file does not exist, creates a new file for reading and
>>> list1.extend(list2) 3. Attempt any THREE of the following: 12 M writing.
>>> list1
[1, 2, 3, 4, 5, 'A', 'B', 'C'] a) Describe various modes of file object? Explain any two in detail. 4M 9 a Opens a file for appending. The file pointer is at the end
9 list.pop(item=list[- It deletes and returns the >>> list1 of the file if the file exists.
1]) last element of the list. [1, 2, 7, 3, 4, 5, 3]
>>> list1.pop()
3
Page No: 5 | 20 Page No: 6 | 20 Page No: 7 | 20
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________ __________________________________________________________________________________________________
That is, the file is in the append mode. If the file does Else Statement: The else block just after for/while is executed only when the loop is NOT It is clear that method overloading is not supported in python but that does not mean
not exist, it creates a new file for writing. terminated by a break statement. The else keyword in a for loop specifies a block of code to that we cannot call a method with different number of arguments. There are a couple
be executed when the loop is finished: of alternatives available in python that make it possible to call the same method but
10 ab Opens a file for appending in binary format. The file with different number of arguments.
Example:
pointer is at the end of the file if the file exists. That is, for i in range(1, 4):
the file is in the append mode. If the file does not exist, print(i)
Method Overriding: Overriding is the ability of a class to change the implementation
else: # Executed because no break in for of a method provided by one of its base class. Method overriding is thus a strict part
it creates a new file for writing.
print("Finally Exit”) of the inheritance mechanism. To override a method in the base class, we must define
Output: a new method with same name and same parameters in the derived class. Overriding
11 a+ Opens a file for both appending and reading. The file
1 is a very important part of OOP since it is the feature that makes inheritance exploit
pointer is at the end of the file if the file exists. The file 2 its full power. Through method overriding a class may "copy" another class, avoiding
opens in the append mode. If the file does not exist, it 3 duplicated code, and at the same time enhance or customize part of it.
creates a new file for reading and writing. Finally Exit
c) T = ('spam, Spam', SPAM!', 'SaPm') 4M Example: For method overriding.
12 ab+ Opens a file for both appending and reading in binary print (T [2]) class A: # parent class
format. The file pointer is at the end of the file if the print (T[-2]) "Parent Class"
print (T[2:])
file exists. The file opens in the append mode. If the file def display(self):
print (List (T))
does not exist, it creates a new file for reading and Input
print ('This is base class.')
Ans Each Print
writing. T = ('spam’, ‘Spam', ‘SPAM!', 'SaPm') class B(A): #derived class
Statement/
"Child/Derived class"
output for 1 M
13 t Opens in text mode (default). Python statement Output def display(self):
print (T [2]) SPAM! print ('This is derived class.')
14 b Opens in binary mode print (T[-2]) SPAM! obj = B() # instance of child
print (T[2:]) [‘SPAM!', 'SaPm'] obj.display() # child calls overridden method
15 + Opens a file for updating (reading and writing). print (list (T)) ['spam', 'Spam', 'SPAM!', 'SaPm'] Output:
This is derived class.
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________ __________________________________________________________________________________________________
>>> first_set ^ second_set # using the `^` operator structures to learn in Python are List (list), Dictionary (dict), Tuple (tuple), and Set Sets: Sets in Python are the non-duplicative data structure. That means they
{1, 2, 3, 7, 8, 9} (set). can only store one of an element. Sets are declared with curly braces like
b) Explain building blocks of python. 6M Strings dictionaries, but do not contain ‘:’ in them. The example code shows how to
Strings in Python are assigned with single or double quotations. As in many turn a list into a set, access set elements by index, add to a set, and remove
Ans 1) Python Identifiers: Variable name is known as identifier. Any 6 building other programming languages, characters in strings may be accessed as if from a set.
To name an identifier following are the rules: blocks=6M accessing an array. In the example below we’ll assign a string to a variable,
The first character of the variable must be an alphabet or underscore ( _ ). # we can turn a list into a set
access the first element, check for a
All the characters except the first character may be an alphabet of lower-case(a-z), x = ['a', 'a', 'b', 'c', 'c']
substring, and check the length of the string.
upper-case (A-Z), underscore or digit (0-9). x = set(x)
Identifier name must not contain any white-space, or special character (!, @, #, %, ^,
x = 'abcd'
&, *).
Identifier name must not be similar to any keyword defined in the language. o Numbers: Integers and Floats in Python are both Number types. They can
5) Control structures: Control structures are used to determine the flow of execution
Identifier names are case sensitive for example my name, and MyName is not the interact with each other, they can be used in all four operations. In the
of a Python program. Examples of control structures in Python include if-else
same. example code we’ll explore how these numbers can interact.
statements, for and while loops, and try-except blocks.
Eg: a,b,c=5,10,15 x = 2.5
y=2
6) Functions: Functions are reusable blocks of code that perform specific tasks. In
2) Reserved Words
The following list shows the Python keywords. These are reserved words and cannot use Python, functions are defined using the def keyword.
them as constant or variable or any other identifier names. All the Python keywords contain Boolean: Boolean variables in Python are either True or False. They will also
lowercase letters only. return True for 1 and False for 0. The example shows how to assign either 7) Modules: Python modules are files that contain Python code and can be imported
True or False to a variable in Python into other Python programs to reuse code and simplify development.
x = True
y = False 8) Packages: Packages are collections of related Python modules that can be installed
and imported together. Packages are commonly used in Python for organizing and
distributing libraries and tools.
Lists: Lists in Python are represented with brackets. Like characters in a string, c) Write a program illustrating use of user defined package in python. 6M
the elements in a list can be accessed with brackets. Lists can also be
enumerate‘d on to return both the index and the element. We’ll go over Ans # student.py Create package:
enumerate when we cover for loops in Python. The example code shows how class Student: 2m
to declare lists, print elements in them, add to them, and remove from them. def __init__(self, student):
self.name = student['name'] Importing
x = [10, 25, 63, 104] self.gender = student['gender'] packages: 2m
y = ['a', 'q', 'blah'] self.year = student['year']
Logic: 2m
3) Indentation: Python provides no braces to indicate blocks of code for class and function Dictionaries: Dictionaries in Python are a group of key-value pairs. def get_student_details(self): (Any
definitions or flow control. Blocks of code are denoted by line indentation, which is Dictionaries are declared with curly braces and their entries can be accessed return f"Name: {self.name}\nGender: {self.gender}\nYear: {self.year}"
compulsory.
Similar/Suitable
in two ways, a) with brackets, and b) with .get. The example code shows how other
The number of spaces in the indentation is variable, but all statements within the block
we can access items in a dictionary. logic/program
must be indented the same amount. For example –
# faculty.py can consider)
_dict = { class Faculty:
if True: 'a': 'Sally sells sea shells',
print "True" def __init__(self, faculty):
'b': 'down by the seashore' self.name = faculty['name']
else:
print "False" } self.subject = faculty['subject']
Thus, in Python all the continuous lines indented with same number of spaces would form def get_faculty_details(self):
Tuples: Tuples is an immutable sequence in Python. Unlike lists, you can’t move
a block. return f"Name: {self.name}\nSubject: {self.subject}"
objects out of order in a Tuple. Tuples are declared with parenthesis and must
contain a comma (even if it is a tuple of 1). The example below shows how to add
4) Python Types: The basic types in Python are String (str), Integer (int), Float tuples, get a tuple from a list, and return information about it. # testing.py
(float), and Boolean (bool). There are also built in data structures to know when you x = (a, b) # importing the Student and Faculty classes from respective files
learn Python. These data structures are made up of the basic types, you can think of from student import Student
them like Legos, the data structures are made out of these basic types. The core data from faculty import Faculty
Page No: 14 | 20 Page No: 15 | 20 Page No: 16 | 20
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________ __________________________________________________________________________________________________
Ans class Animal: #super class Any other add():
# creating dicts for student and faculty suitable Adds an element to the set. If an element is already exist in the set, then it does not
student_dict = {'name' : 'ABC', 'gender': 'Male', 'year': '3'} # attribute and method of the parent class program can add that element.
faculty_dict = {'name': 'XYZ', 'subject': 'Programming'} name = "" consider Example:
def eat(self): s = {'g', 'e', 'k', 's'}
# creating instances of the Student and Faculty classes print("I can eat") # adding f into set s
student = Student(student_dict) s.add('f')
# inherit from Animal Class creation:
faculty = Faculty(faculty_dict) print('Set after updating:', s)
class Dog(Animal): sub(2 M class 2m
# getting and printing the student and faculty details Inherit one output:
print(student.get_student_details()) # new method in subclass Set after updating: {'s', 'f', 'e', 'g', 'k'}
class to another:
print() def display(self):
2m
print(faculty.get_faculty_details()) # access name attribute of superclass using self discard():
print("My name is ", self.name) Logic: 2m Removes the element from the set
Example:
Output : # create an object of the subclass s = {'g', 'e', 'k', 's'}
Name: ABC labrador = Dog() print('Set before discard:', s)
Gender: Male
Year: 3
s.discard('g')
# access superclass attribute and method print('\nSet after discard g:', s)
labrador.name = "Rohu"
Name: XYZ
Subject: Programming
labrador.eat() Output:
# call subclass method Set before discard: {'s', 'e', 'k', 'g'}
Set after discard g: {'s', 'e', 'k'}
labrador.display()
6. Attempt any TWO of the following: 12 M
Output: remove():
a) Write a program to create class student with Roll no. and Name and 6M I can eat Removes the specified element from the set. If the specified element not found, raise
display its contents My name is Rohu an error.
Example:
Ans class Student: Create Class: s = {'g', 'e', 'k', 's'}
def __init__(self, name, rollno): 3m c) List and explain any four built-in functions on set. 6M
print('Set before remove:', s)
self.name = name s.remove('e')
self.rollno = rollno Display Ans Built-in Functions with Set Listing: 2m
Method: 3m add() print('\nSet after remove e:', s)
discard() Explanation of
def __str__(self): any two Output:
return f"{self.name}({self.rollno})" copy()
remove() function: 4m Set before remove: {'s', 'k', 'e', 'g'}
clear() Set after remove e: {'s', 'k', 'g'}
(2 M each)
s1 = Student("ABC", 32) union()
print(s1) difference() clear():
intersection() Removes all elements from the set
Output: discard() Example:
ABC 32 issubset() s = {'g', 'e', 'k', 's'}
issuperset() print('Set before clear:', s)
b) Write program to implement concept of inheritance in python. 6M pop() s.clear()
update() print('\nSet after clear:', s)
symmetric_difference() Output:
Set before clear: {'g', 'k', 's', 'e'}
Set after clear: set()
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous) (Autonomous)
m
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________ __________________________________________________________________________________________________
SUMMER – 2023 EXAMINATION • Python provides ‘in’ and ‘not in’ operators which are called membership
sb
sb
copy(): Returns a shallow copy of the set
Example: Model Answer – Only for the Use of RAC Assessors operators and used to test whether a value or variable is in a sequence.
s = {'g', 'e', 'k', 's'}
te
te
p=s.copy() Subject Name: Programming with Python Subject Code: 22616 c) Write down the output of the following Python code 2M
al
al
print("original set:",s) >>>indices-['zero','one','two',' three,' four, five']
print("Copied set:",p) Important Instructions to examiners: XXXXX i) >>>indices[:4]
lc
lc
1) The answers should be examined by key words and not as word-to-word as given in the model answer scheme.
ii) >>>indices[:-2]
2) The model answer and the answer written by candidate may vary but the examiner may try to assess the
le
le
Output:
understanding level of the candidate. Ans Output as follows: 1 M for
original set: {'k', 's', 'g', 'e'}
ar
ar
3) The language errors such as grammatical, spelling errors should not be given more Importance (Not applicable for i) >>>indices[:4] each
Copied set: {'k', 's', 'g', 'e'} subject English and Communication Skills.
[zero, one, two, three] correct
.c
.c
4) While assessing figures, examiner may give credit for principal components indicated in the figure. The figures
ii) >>>indices[:-2] output
drawn by candidate and model answer may vary. The examiner may give credit for any equivalent figure drawn.
o
Union():The set.union() method returns a new set with distinct elements from all the 5) Credits may be given step wise for numerical problems. In some cases, the assumed constant values may vary and [zero, one, two, three]
given sets.
m
there may be some difference in the candidate’s answers and model answer.
Example: 6) In case of some questions credit may be given by judgement on part of examiner of relevant answer based on d) Describe any two data conversion function. 2M
nums1 = {1, 2, 2, 3, 4, 5} candidate’s understanding.
nums2 = {4, 5, 6, 7, 7, 8} Ans • int(x [,base]): Converts x to an integer. base specifies the base if x is a Any 2
7) For programming language papers, credit may be given to any other program based on equivalent concept.
distinct_nums = nums1.union(nums2) string. Conversion
8) As per the policy decision of Maharashtra State Government, teaching in English/Marathi and Bilingual (English +
print("The union of two sets is: ", distinct_nums) Marathi) medium is introduced at first year of AICTE diploma Programme from academic year 2021-2022. Hence if Example: x=int('1100',base=2)=12 function
the students in first year (first and second semesters) write answers in Marathi or bilingual language (English • long(x [,base]): Converts x to a long integer. base specifies the base if x is 2M
Output: +Marathi), the Examiner shall consider the same and assess the answer based on matching of concepts with model a string.
The union of two sets is: {1, 2, 3, 4, 5, 6, 7, 8} answer. Example: x=long(‘123’base=8)=83L
Difference():The set.difference() method returns the new set with the unique elements • float(x): Converts x to a floating point number.
Q. Sub Answer Marking
that are not in the other set passed as a parameter. Example: x=float('123.45')=123.45
No. Q. Scheme
Example: N. • complex(real[,imag]) : Creates a complex number.
nums1 = {1, 2, 2, 3, 4, 5} Example: x=complex(1,2) = (1+2j)
nums2 = {4, 5, 6, 7, 8, 8} 1 Attempt any FIVE of the following: 10 M • str(x): Converts object x to a string representation.
nums3 = nums1.difference(nums2)
a) List features of Python. 2M Example: x=str(10) = ‘10’
nums4 = nums2.difference(nums1)
• repr(x): Converts object x to an expression string
print("nums1 - nums2: ", nums3)
Ans Features of Python are listed below: Any 2, Example: x=repr(3) = 3
print("nums2 - nums1: ", nums4)
• Easy to Learn and Use 1 M each • repr(x): Evaluates a string and returns an object.
Output: • Interpreted Language Example: x=eval('1+2') = 3
nums1 - nums2: {1, 2, 3} • Interactive Mode • tuple(s): Converts s to a tuple
nums2 - nums1: {8, 6, 7} • Free and Open Source Example:
• Platform Independence/Cross-platform Language/Portable x=tuple('123') = ('1', '2', '3')
Intersection():The set.intersection() method returns a new set with the elements that
• Object-Oriented Language x=tuple([123]) = (123,)
are common in the given sets.
Example: • Extensible • list(s): Converts s to a list
x = {"apple", "banana", "cherry"} Example:
b) Describe membership operators in python 2M
y = {"google", "microsoft", "apple"} x=list('123') = ['1', '2', '3']
z = x.intersection(y) Ans • The membership operators in Python are used to find the existence of a particular 2 M for x=list(['12'] = ['12']
print(z) element in the sequence, and used only with sequences like string, tuple, list, proper • set(s): Converts s to a set
dictionary etc. explanation Example:
Output: • Membership operators are used to check an item or an element that is part of a x=set('Python')
apple
string, a list or a tuple. A membership operator reduces the effort of searching an = {'y', 't', 'o', 'P', 'n', 'h'}
element in the list. • dict(d): Creates a dictionary. d must be a sequence of (key, value) tuples.
m
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________ __________________________________________________________________________________________________
Syntax: os.mkdir(“newdir”)
sb
sb
sb
Example: Output:
dict={'id':'11','name':'vijay'}
Example: i=1
te
te
te
print(dict)
i=2
={'id': '11', 'name': 'vijay'} >>> import os
al
al
al
i=3
• chr(x): Converts an integer to a character. i=4
lc
lc
lc
Example: x=chr(65) = ‘A’ >>> os.mkdir("testdir") i=6
•
le
le
le
unichr(x): Converts an integer to a Unicode character i=7
g) Describe Multiline comment in python. 2M
Example: x=unichr(65) =u’A’ i=8
ar
ar
ar
• ord(x): Converts a single character to its integer value. i=9
Ans • In some situations, multiline documentation is required for a program. If we have 2 M for i=10
.c
.c
.c
Example: x=ord('A')= 65 proper
comments that extend multiple lines, one way of doing it is to use hash (#) in the b) Explain creating Dictionary and accessing Dictionary Elements with 4M
• hex(x): Converts an integer to a hexadecimal string. explanation
om
om
om
beginning of each line. Another way of doing this is to use quotation marks, either example.
Example: x=hex(12) = 0xc ''' or """.
• oct(x): Converts an integer to an octal string. • Similarly, when it sees the triple quotation marks ''' it scans for the next ''' and Ans Creating Dictionary Creating
Example: x=oct(8) = 0o10 ignores any text in between the triple quotation marks. Dictionary
The simplest method to create dictionary is to simply assign the pair of key:values explanation
e) With neat example explain default constructor concept in Python. 2M Example: For multiline comment. to the dictionary using operator (=). with example
• There are two ways for creation of dictionary in python. 2 M,
Ans The default constructor is simple constructor which does not accept any arguments. It’s Explanation '''This is first python program 1. We can create a dictionary by placing a comma-separated list of key:value Accessing
definition has only one argument which is a reference to the instance being constructed. 1 M,
Example Print is a statement''' pairs in curly braces{}. Each key is separated from its associated value by a Dictionary
Example 1: Display Hello message using default constructor. 1M colon: Element with
Example: For creating a dictionary using { }. example 2 M
class Student: >>> dict1={} #Empty dictionary
2. Attempt any THREE of the following: 12 M
>>> dict1
def _ _init_ _(self):
a) Describe Keyword "continue" with example. 4M {}
print("This is non parametrized constructor") >>> dict2={1:"Orange", 2:"Mango", 3:"Banana"} #Dictionary with
Ans • The continue statement in Python returns the control to the beginning of the while Explanation integer keys
def show(self,name): loop. 2M,
>>> dict2
• The continue statement rejects all the remaining statements in the current iteration Example
{1: 'Orange', 2: 'Mango', 3: 'Banana'}
print("Hello",name) of the loop and moves the control back to the top of the loop. 2M
>>> dict3={"name":"vijay", 1:[10,20]} #Dictionary with mixed keys
s1 = Student() Syntax: continue >>> dict3
{'name': 'vijay', 1: [10, 20]}
s1.show("Student1") Example: For continue statement.
2. Python provides a build-in function dict() for creating a dictionary
i=0
Example: Creating directory using dict().
Output: while i<10: >>> d1=dict({1:"Orange",2:"Mango",3:"Banana"})
>>> d2=dict([(1,"Red"),(2,"Yellow"),(3,"Green")])
This is non parametrized constructor i=i+1 >>> d3=dict(one=1, two=2, three=3)
Hello Student1 >>> d1
if i==5:
{1: 'Orange', 2: 'Mango', 3: 'Banana'}
f) Describe mkdir() function. 2M >>> d2
continue
{1: 'Red', 2: 'Yellow', 3: 'Green'}
Ans • We can make a new directory using the mkdir() method. Explanation print("i= ",i) >>> d3
• This method takes in the path of the new directory. If the full path is not specified, 2M {'one': 1, 'two': 2, 'three': 3}
the new directory is created in the current working directory.
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous) (Autonomous)
m
m
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________ __________________________________________________________________________________________________
sb
sb
sb
Accessing Values in a Dictionary 15 '0b1010'
• We can access the items of a dictionary by following ways: with the prefix 0b.
1. Referring to its key name, inside square brackets([]).
te
te
te
• min(list)
Example: For accessing dictionary items [ ] using. • bool()
It returns the item that has the minimum value in a list.
al
al
al
>>> dict1={'name':'vijay','age':40} The bool() function returns the boolean value of a specified object.
>>> dict1['name'] Example:
lc
lc
lc
>>> list1 Example:
'vijay'
>>> bool(1)
le
le
le
>>> dict1['adr'] [1, 2, 3, 4, 5]
Traceback (most recent call last): >>> min(list1) True
ar
ar
ar
File "<pyshell#79>", line 1, in <module> 1
dict1['adr'] • exp()
.c
.c
.c
KeyError: 'adr' The method exp() returns returns exponential of x: ex.
• list(seq)
o
o
>>> x: This is a numeric expression.
Here, if we refer to a key that is not in the dictionary, you’ll get an It converts a tuple into a list.
m
m
exception. This error can be avoided by using get() method. Example: Example:
>>> math.exp(1)
2. Using get() method returns the value for key if key is in the dictionary, else >>> list1 2.718281828459045
None, so that this method never raises a KeyError. [1, 2, 3, 4, 5] >>>
Example: For accessing dictionary elements by get(). >>> list(list1)
>>> dict1={'name':'vijay','age':40} [1, 2, 3, 4, 5]
>>> dict1.get('name') • abs(n) d) Write a Python program to find the factorial of a number provided by the 4M
'vijay' It returns the absolute value of a number. user.
Example:
c) Explain any four Python's Built-in Function with example. 4M >>> abs(10) Ans num=int(input("Enter Number:")) Correct
10 fact=1 program
Ans • len(list) Any 4 Built- if num< 0:
in function 4M
It returns the length of the list. • all() print("Sorry, factorial does not exist for negative numbers")
Example: with example The all() function returns True if all items in an iterable are true, otherwise it elif num == 0:
>>> list1 4M returns False. print("The factorial of 0 is 1")
[1, 2, 3, 4, 5] Example: else:
>>> len(list1) >>> x=[True, True, True] for i in range(1,num + 1):
5 >>> all(x) fact=fact*i
• max(list) True print("The factorial of ",num," is ",fact)
It returns the item that has the maximum value in a list
Example: • any() Output:
>>> list1 The any() function returns True if any item in an iterable are true, otherwise it Enter Number: 5
[1, 2, 3, 4, 5] returns False. If the iterable object is empty, the any() function will return False. The factorial of 5 is 120
>>> max(list1) Example:
5 >>> x=[True, False, True]
>>> any(x)
3. Attempt any THREE of the following: 12 M
• sum(list) True
Calculates sum of all the elements of list. a) Write a python program to input any two tuples and interchange the tuple 4M
Example: • bin() variables.
>>>list1 The bin() function returns the binary version of a specified integer. The result
will always start >>> bin(10) Ans def interchange_tuples(tup1, tup2): Any correct
[1, 2, 3, 4, 5]
Example: programming
>>>sum(list1)
m
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________ __________________________________________________________________________________________________
sb
sb
sb
new_tup1 = tup2 logic 4 M result = a & b specified number of positions. Zeros are shifted in from the left side.
new_tup2 = tup1 print(result) # Output: 2 (binary: 0010) Example:
te
te
te
return new_tup1, new_tup2 2) Bitwise OR (|): Performs a bitwise OR operation on the corresponding bits of two a = 10 # binary: 1010
al
al
al
numbers. Each bit of the output is 0 if the corresponding bits of both operands are
# Input two tuples result = a >> 2
lc
lc
lc
0; otherwise, it is 1.
le
le
le
tuple1 = tuple(input("Enter the elements of the first tuple (separated by commas): Example: print(result) # Output: 2 (binary: 10)
").split(","))
ar
ar
ar
a = 10 # binary: 1010 c) With neat example differentiate between readline () and readlines ( ) 4M
tuple2 = tuple(input("Enter the elements of the second tuple (separated by commas): functions in file-handling.
.c
.c
.c
").split(",")) b = 6 # binary: 0110
Ans readline(): This method reads a single line from the file and returns it as a string. It moves readline()
om
om
om
result = a | b the file pointer to the next line after reading. If called again, it will read the subsequent explanation
# Interchange the tuples print(result) # Output: 14 (binary: 1110) line. for 1 M and
Example for
result_tuple1, result_tuple2 = interchange_tuples(tuple1, tuple2) 3) Bitwise XOR (^): Performs a bitwise XOR (exclusive OR) operation on the # Open the file in read mode 1M
corresponding bits of two numbers. Each bit of the output is 1 if the file = open("example.txt", "r")
corresponding bits of the operands are different; otherwise, it is 0. and
readlines()
# Display the result # Read the first line
Example: explanation
line1 = file.readline() for 1 M and
print("Interchanged tuples:") a = 10 # binary: 1010 Example for
print("Tuple 1:", result_tuple1) print(line1) 1M
b = 6 # binary: 0110
print("Tuple 2:", result_tuple2) result = a ^ b
output: # Read the second line
print(result) # Output: 12 (binary: 1100)
Enter the elements of the first tuple (separated by commas): 10,20 line2 = file.readline()
4) Bitwise NOT (~): Performs a bitwise NOT operation on a single operand, which
inverts all the bits. It returns the complement of the given number. print(line2)
Enter the elements of the second tuple (separated by commas): 30,40
Example:
Interchanged tuples:
a = 10 # binary: 1010 # Close the file
Tuple 1: ('30', '40')
result = ~a file.close()
Tuple 2: ('10', '20')
print(result) # Output: -11 (binary: -1011) readlines(): This method reads all lines from the file and returns them as a list of strings.
b) Explain Bitwise operator in Python with appropriate example. 4M
Each line is an individual element in the list. It reads the entire file content and stores it in
5) Bitwise left shift (<<): Shifts the bits of the left operand to the left by a specified memory.
Ans Bitwise operators available in Python: Any four number of positions. Zeros are shifted in from the right side.
operator
1) Bitwise AND (&): Performs a bitwise AND operation on the corresponding bits Example:
(Each for 1 Example:
of two numbers. Each bit of the output is 1 if the corresponding bits of both M) # Open the file in read mode
operands are 1; otherwise, it is 0. a = 10 # binary: 1010
file = open("example.txt", "r")
Example: result = a << 2
a = 10 # binary: 1010 print(result) # Output: 40 (binary: 101000)
# Read all lines
b = 6 # binary: 0110 6) Bitwise right shift (>>): Shifts the bits of the left operand to the right by a
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous) (Autonomous)
m
m
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________ __________________________________________________________________________________________________
sb
sb
sb
lines = file.readlines() # Access the attributes using the self parameter is placed at the beginning of the file. This is the default mode.
3 r+ Opens a file for both reading and writing. The file pointer placed at
print(my_car.make) # Output: Toyota the beginning of the file.
te
te
te
# Close the file print(my_car.model) # Output: Corolla 4 rb+ Opens a file for both reading and writing in binary format. The
al
al
al
file pointer placed at the beginning of the file.
file.close() print(my_car.year) # Output: 2022 5 w Opens a file for writing only. Overwrites the file if the file
lc
lc
lc
exists. If the file does not exist, creates a new file for writing.
le
le
le
# Print each line 6 wb Opens a file for writing only in binary format. Overwrites the
file if the file exists. If the file does not exist, creates a new file
ar
ar
ar
for line in lines: # Call the method using the self parameter
for writing
7 w+ Opens a file for both writing and reading. Overwrites the
.c
.c
.c
print(line) car_info = my_car.get_info()
existing file if the file exists. If the file does not exist, creates a
o
o
d) Describe 'Self Parameter with example. 4M print(car_info) # Output: Make: Toyota, Model: Corolla, Year: 2022 new file for reading and writing.
m
m
8 wb+ Opens a file for both writing and reading in binary format.
Ans In Python, the self parameter is a convention used in object-oriented programming (OOP) Explanation Overwrites the existing file if the file exists. If the file does not
to refer to the instance of a class within the class itself. It allows you to access the 2 M and exist, creates a new file for reading
# Call the method that does not require any additional parameters
attributes and methods of the class from within its own methods. The name self is not a
example 2 and writing
keyword in Python, but it is widely adopted and recommended as a convention. my_car.start_engine() # Output: Engine started!
M 9 a Opens a file for appending. The file pointer is at the end of the
Example: file if the file exists. That is, the file is in the append mode. If
the file does not exist, it creates a new file for writing.
class Car: 4. Attempt any THREE of the following: 12 M 10 ab Opens a file for appending in binary format. The file pointer is
at the end of the file if the file exists. That is, the file is in the
def __init__(self, make, model, year): a) Differentiate between list and Tuple. 4M append mode. If the file does not exist, it creates a new file for
self.make = make writing
Ans Any 4 11 a+ Opens a file for both appending and reading. The file pointer
self.model = model correct point is at the end of the file if the file exists. The file opens in the
List Tuple 4M append mode. If the file does not exist, it creates a new file for
self.year = year reading and writing.
Lists are mutable Tuples are immutable
12 ab+ Opens a file for both appending and reading in binary format.
The implication of iterations is Time- The implication of iterations is The file pointer is at the end of the file if the file exists. The file
def get_info(self): consuming comparatively Faster opens in the append mode. If the file does not exist, it creates
a new file for reading and writing.
info = f"Make: {self.make}, Model: {self.model}, Year: {self.year}" The list is better for performing A Tuple data type is appropriate for
13 t Opens in text mode (default).
operations, such as insertion and deletion. accessing the elements
return info 14 b Opens in binary mode.
Lists consume more memory Tuple consumes less memory as 15 + Opens a file for updating (reading and writing).
compared to the list c) Write a program to show user defined exception in Python. 4M
def start_engine(self): Lists have several built-in methods Tuple does not have many built-in Ans class MyException(Exception): Any correct
methods. logic
print("Engine started!") def __init__(self, message): program 4 M
Unexpected changes and errors are more In a tuple, it is hard to take place.
likely to occur self.message = message
# Create an instance of the Car class
b) Explain any four file modes in Python. 4M
my_car = Car("Toyota", "Corolla", 2022) # Function that raises the custom exception
Ans Sr. No. Mode Description 1 Mode for 1
1 r Opens a file for reading only. The file pointer is placed at the M def divide_numbers(a, b):
beginning of the file. This is the default mode.
2 rb Opens a file for reading only in binary format. The file pointer
Page No: 12 | 24 Page No: 13 | 24 Page No: 14 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous) (Autonomous)
m
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________ __________________________________________________________________________________________________
sb
sb
sb
if b == 0: copying its definition into each program. print("The string is not a palindrome.")
raise MyException("Division by zero is not allowed!") • In Python we can put definitions in a file and use them in a script or in an interactive output:
te
te
te
instance of the interpreter. Such a file is called a module.
return a / b Enter a string: madam
al
al
al
Use of module in python :
The string is a palindrome.
lc
lc
lc
Code organization: Modules allow you to organize related code into separate files,
le
le
le
# Main program making it easier to navigate and maintain large projects. Enter a string: abc
ar
ar
ar
try: Code reusability: Modules can be imported and reused in multiple programs, enabling The string is not a palindrome.
code reuse and reducing duplication.
.c
.c
.c
num1 = int(input("Enter the numerator: ")) b) Write a Python program to calculate sum of digit of given number using 6M
Encapsulation: Modules provide a way to encapsulate code and hide the implementation function.
om
om
om
num2 = int(input("Enter the denominator: "))
details, allowing users to focus on the functionality provided by the module.
Ans def calculate_digit_sum(number): Any correct
Name spacing: Modules help avoid naming conflicts by providing a separate namespace logic
result = divide_numbers(num1, num2) for the names defined within the module. # Convert the number to a string program 6M.
5. Attempt any TWO of the following: 12 M # Initialize a variable to store the sum
except MyException as e: a) Write a Python Program to check if a string is palindrome Or not. 6M digit_sum = 0
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous) (Autonomous)
m
m
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________ __________________________________________________________________________________________________
sb
sb
sb
num = int(input('How many numbers: ')) program 6M set1 = {1, 2, 3} numbers.clear()
te
te
numbers = int(input('Enter number ')) intersection_set = set1.intersection(set2) 7) isdisjoint():
al
al
al
The isdisjoint() method in Python's set class is used to check whether two sets
list.append(numbers) print(intersection_set) # Output: {2, 3}
lc
lc
lc
have any common elements. It returns True if the sets are disjoint (i.e., they have
no common elements), and False otherwise.
le
le
le
print("Maximum element in the list is :", max(list), "\nMinimum element in the list is :", 3) Difference:
Example:
min(list)) # Example 1
ar
ar
ar
Difference operation on two sets set1 and set2 returns all the elements which are
present on set1 but not in set2. set1 = {1, 2, 3, 4}
output:
.c
.c
.c
set2 = {5, 6, 7}
Example: set3 = {3, 4, 5}
How many numbers: 5
o
o
m
m
set1 = {1, 2, 3, 4, 5} print(set1.isdisjoint(set2)) # True, no common elements
Enter number 10
set2 = {3, 4} print(set1.isdisjoint(set3)) # False, both sets have elements 3 and 4
Enter number 20
difference_set = set1.difference(set2)
Enter number 30 # Example 2
print(difference_set) # Output: {1, 2, 5} fruits = {"apple", "banana", "orange"}
Enter number 40
colors = {"red", "green", "blue"}
4) add(element):
Enter number 50
This function adds an element to a set. print(fruits.isdisjoint(colors)) # True, no common elements
Maximum element in the list is : 50
Example:
Minimum element in the list is : 10 # Example 3
fruits = {"apple", "banana", "cherry"} setA = {1, 2, 3}
fruits.add("orange") setB = {4, 5, 6}
6. Attempt any TWO of the following: 12 M
print(fruits) # Output: {'apple', 'banana', 'cherry', 'orange'} print(setA.isdisjoint(setB)) # True, no common elements
a) Explain any six set function with example. 6M
8) pop():method in Python's set class is used to remove and return an arbitrary
Ans 1) union():Return a new set containing the union of two or more sets 1 function element from the set. Since sets are unordered collections, there is no guarantee
5) remove(element): on which element will be popped.
for 1 M each
Example: Example:
This function removes an element from a set.
fruits = {"apple", "banana", "orange", "grape"}
set1 = {1, 2, 3}
Example:
set2 = {3, 4, 5} # Remove and return an arbitrary element from the set
numbers = {1, 2, 3, 4, 5} popped_element = fruits.pop()
union_set = set1.union(set2)
numbers.remove(3)
print(popped_element) # Output: an arbitrary element from the set
print(union_set) # Output: {1, 2, 3, 4, 5} print(fruits) # Output: the modified set after popping an element
print(numbers) # Output: {1, 2, 4, 5}
2) Intersection:
6) clear(): 9) update():The update() method in Python's set class is used to update a set by
Intersection operation performed on two sets returns all the elements which are adding elements from another iterable or set. It modifies the set in place by adding
This function removes all elements from a set, making it an empty set. all the elements from the iterable or set specified.
common or in both the sets.
Example: Example:
Example: set1 = {1, 2, 3}
numbers = {1, 2, 3, 4, 5} set2 = {3, 4, 5}
m
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________ __________________________________________________________________________________________________
sb
sb
sb
set1.update(set2) # Read and set student information Example:
student.read_student_info() # Base class
te
te
te
print(set1) # Output: {1, 2, 3, 4, 5}
class Animal:
al
al
al
b) Design a class student with data members : name, roll no., department, 6M
# Print student information def __init__(self, name):
lc
lc
lc
mobile no. Create suitable methods for reading and printing student
information.
le
le
le
student.print_student_info() self.name = name
ar
ar
ar
Ans class Student: Any correct output:
logic
.c
.c
.c
def __init__(self): program 6 Enter student name: raj def speak(self):
M
om
om
om
self.name = "" Enter roll number: 11 print("Animal speaks")
self.roll_no = "" Enter department: computer
self.department = "" Enter mobile number: 123456 # Derived class inheriting from Animal
self.mobile_no = "" Student Information: class Dog(Animal):
Name: raj def speak(self):
def read_student_info(self): Roll Number: 11 print("Dog barks")
self.name = input("Enter student name: ") Department: computer
self.roll_no = input("Enter roll number: ") Mobile Number: 123456 # Derived class inheriting from Animal
self.department = input("Enter department: ") c) With suitable example explain inheritance in Python. 6M class Cat(Animal):
self.mobile_no = input("Enter mobile number: ") Ans In inheritance objects of one class procure the properties of objects of another class. Explanation def speak(self):
Inheritance provide code usability, which means that some of the new features can be 3 M and
print("Cat meows")
added to the code while using the existing code. The mechanism of designing or Correct
def print_student_info(self): constructing classes from other classes is called inheritance. example 3 M
print("Student Information:") • The new class is called derived class or child class and the class from which this # Create instances of derived classes
derived class has been inherited is the base class or parent class.
print("Name:", self.name) dog = Dog("Buddy")
• In inheritance, the child class acquires the properties and can access all the data
print("Roll Number:", self.roll_no) members and functions defined in the parent class. A child class can also provide its cat = Cat("Whiskers")
specific implementation to the functions of the parent class.
print("Department:", self.department)
Syntax:
print("Mobile Number:", self.mobile_no) # Call the speak method of the derived classes
class A:
dog.speak() # Output: Dog barks
# properties of class A
# Create an instance of the Student class cat.speak() # Output: Cat meows
class B(A):
student = Student()
# class B inheriting property of class A
# more properties of class B
(Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
te
Model Answer – Only for the Use of RAC Assessors Model Answer – Only for the Use of RAC Assessors
lc
Subject: Programming with Python Subject Code: 22616 Subject: Programming with Python Subject Code: 22616
le
1) The answers should be examined by key words and not as word-to-word as given Ans. Membership Operators: The membership operators in Python are Each
in the model answer scheme. used to find the existence of a particular element in the sequence and operator 1M
.c
2) The model answer and the answer written by candidate may vary but the examiner used only with sequences like string, tuple, list, dictionary etc.
may try to assess the understanding level of the candidate.
o
3) The language errors such as grammatical, spelling errors should not be given more
Sr. Operator Description Example
m
Page 1 / 23 Page 2 / 23
Page No: 24 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
Subject: Programming with Python Subject Code: 22616 Subject: Programming with Python Subject Code: 22616 Subject: Programming with Python Subject Code: 22616
d) List different object oriented features supported by Python 2M • a: open an existing file for append operation. It won‟t override
Ans. The main object-oriented features supported by Python:- Listing any existing data. Syntax:
Classes four
• r+: To read and write data into the file. The previous data in the file if condition1:
features ½
Objects M each will be overridden.
# Code block to execute if condition1 is True
Encapsulation • w+: To write and read data. It will override existing data.
elif condition2:
Inheritance # Code block to execute if condition1 is False and condition2 is
• a+: To append and read data from the file. It won‟t override existing True
Polymorphism
Abstraction
data. else:
2. Attempt any THREE of the following: 12M # Code block to execute if both condition1 and condition2 are
e) State how to perform comments in Python 2M False
a) Explain decision making statements if-else, if-elif-else with 4M
Ans. Single line comment: Single-line comments are created simply by Correct
example. Explanation
beginning a line with the hash (#) character, and they are explanation of each Example:
of each 1M Ans. Decision-making statements in Python allow the execution of specific
automatically terminated by the end of line. statement
age = 25
blocks of code based on conditions. Python provides several with
Example:
constructs for decision-making if age < 13:
# print is a statement print(„Hello Python‟) example 2M
Multi line comment: Python multi-line comment is a piece of text print("You are a child.")
if-else Statement elif 13 <= age <= 19:
enclosed in a delimiter (""") Triple quotation marks.
The if-else statement is used to test a condition. If the condition is
Example: print("You are a teenager.")
True, the code inside the if block is executed. If the condition is
""" Multi-line comment used elif 20 <= age <= 59:
False, the code inside the else block is executed.
print("Python Comments") """ print("You are an adult.")
or To add a multiline comment you could insert a # for each line:
Syntax: else:
Example:
if condition: print("You are a senior.")
#This is a comment
# Code block to execute if the condition is True
#written in
else: b) Describe any four methods of list in python. 4M
#more than just one line print("Hello, World!")
# Code block to execute if the condition is False Ans. Four commonly used methods of lists in Python: Description
f) Define class and object 2M Example: of each
Ans. Note: Any other relevant definition shall be considered Correct age = 16 1. append(): Adds a single item to the end of the list. method 1M
Class: A class is a user-defined blueprint or prototype from which definition of if age >= 18: Syntax:
each 1M
objects are created. Classes provide a means of bundling data and print("You are eligible to vote.") list.append(item)
functionality together. else: Example:
Object: An object is an instance of a class that has some attributes print("You are not eligible to vote.") fruits = ['apple', 'banana', 'cherry']
and behavior. Objects can be used to access the attributes of the class.
fruits.append('orange') # Adds 'orange' to the end of the list
if-elif-else Statement print(fruits)
g) List different modes of opening file in Python 2M The if-elif-else statement is used when there are multiple conditions
Ans. Modes for opening file: Any two
to check. Python evaluates each if or elif condition in sequence. If
correct
• r: open an existing file for a read operation. modes 1M one of the conditions evaluates to True, the corresponding block of 2. remove():Removes the first occurrence of a specified element
• w: open an existing file for a write operation. If the file already each code is executed, and the rest are skipped. If none of the if or elif from the list.
contains some data then it will be overridden. conditions are True, the code inside the else block is executed. Syntax:
list.remove(item)
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
Subject: Programming with Python Subject Code: 22616 Subject: Programming with Python Subject Code: 22616 Subject: Programming with Python Subject Code: 22616
3. pop() : Removes and returns an item at a specified index from the r' (Read Mode)
Here, there is a directory named pkg that contains two modules,
list. If no index is provided, it removes and returns the last item. Opens the file for reading only. The file must already exist, and an
mod1.py and mod2.py. The contents of the modules are:
Syntax: error (FileNotFoundError) will be raised if the file does not exist.
mod1.py
list.pop(index) # Removes and returns the item at the given index Example:
def m1():
list.pop() # Removes and returns the last item try:
print("first module")
Example: file = open('example.txt', 'r') # Opens the file for reading
mod2.py
fruits = ['apple', 'banana', 'cherry'] content = file.read() # Reads the entire content of the file
def m2():
popped_item = fruits.pop(1) # Removes and returns the item at index print(content)
print("second module")
1 except FileNotFoundError:
If the pkg directory resides in a location where it can be found, you
print(fruits) # List after removal print("File not found!")
can refer to the two modules with dot
print(popped_item) # The removed item finally:
notation(pkg.mod1, pkg.mod2) and import them with the syntax:
4. sort() : Sorts the items of the list in ascending order (by default). It file.close() # Always close the file after use
Syntax-1
can also sort in descending order by passing an argument to the
import <module_name>[, <module_name> ...] 'w' (Write Mode)
reverse parameter.
Example: Opens the file for writing. If the file already exists, it overwrites the
Syntax:
>>>import pkg.mod1, pkg.mod2 file (erases its content). If the file does not exist, it is created.
list.sort()
>>> pkg.mod1.m1() Example:
Example:
first module with open('example.txt', 'w') as file: # Opens for writing, creates file
numbers = [5, 3, 8, 1, 2]
Syntax-2: if it doesn't exist
numbers.sort() # Sorts the list in ascending order
from <module_name> import <name(s)> file.write("Hello, World!") # Writes to the file
print(numbers)
Example: 3. Attempt any THREE of the following: 12M
>>> from pkg.mod1 import m1 a) Explain identity and assignment operators with example 4M
c) Write a program illustrating use of user defined package in 4M >>> m1()
2M for
Ans. Identity operators in Python are used to compare the memory 2M for
Python. first module addresses of two objects, determining whether two variables or identity and
Ans. defining 2M for
A package is a hierarchical file directory structure that defines a package objects reference the same memory location. There are two primary
d) Describe various modes of file object? Explain any two in detail. 4M assignment
single Python application environment that consists of modules and identity operators in Python.
2M for
Ans. r': Read (default mode) operators
subpackages and sub-subpackages, and so on. Packages allow for a 'w': Write (creates a new file or truncates an existing file) Description
importing
hierarchical structuring of the module namespace using dot notation. of any four 1) is operator: Returns True if two variables refer to the same
package in 'x': Exclusive creation (fails if the file exists) modes 2M
Creating a package is quite straightforward, since it makes use of the program memory location.
'a': Append (adds content to the end of the file)
operating system‟s inherent hierarchical file structure. 'b': Binary (used with other modes to handle binary files)
Subject: Programming with Python Subject Code: 22616 Subject: Programming with Python Subject Code: 22616 Subject: Programming with Python Subject Code: 22616
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
Subject: Programming with Python Subject Code: 22616 Subject: Programming with Python Subject Code: 22616 Subject: Programming with Python Subject Code: 22616
Subject: Programming with Python Subject Code: 22616 Subject: Programming with Python Subject Code: 22616 Subject: Programming with Python Subject Code: 22616
try:
3) Pass statement Python does not support method overloading, that is, it is not possible ans=a/b
The pass statement is used when a statement is syntactically to define more than one method with the same name in a class in print("ANS :",ans)
necessary, but no code is to be executed. except ZeroDivisionError:
Python.
print("Division by Zero........")
Example : for letter in 'python': This is because method arguments in python do not have a type. A
pass method accepting one argument can be called with an integer value, a output :
print('Last Letter :', letter) string or a double as shown in next Enter the value of a : 10
example. Enter the value of b : 0
Last Letter : n class Demo: Division by Zero..........
b) Illustrate with example Method overloading 4M def method(self, a): d) Write the output for the following if the variable fruit : .banana 4M
Ans. It is the ability to define the method with the same name but with a Ans. >> fruit [:3] Each
2M for print(a) correct
different number of arguments and data types. With this ability one Output : ban
explanation obj= Demo() >> fruit [3:]
output 1M
method can perform different tasks, depending on the number of
obj.method(50) Output : ana
arguments or the types of the arguments given. 2M for
example obj.method('Meenakshi') >> fruit [3:3]
Method overloading is a concept in which a method in a class Output :
obj.method(100.2)
performs operations according to the parameters passed to it. As in >> fruit [:]
Output:
other languages we can write a program having two methods with Output : banana
50
same name but with different number of arguments or order of
Meenakshi e) Write a Python program to read contents from "a.txt" and write 4M
arguments but in python if we will try to do the same we will get the same contents in "b.txt". Any suitable
100.2
following issue with method overloading in Python: Ans. with open("a.txt", "r") as read_file, open("b.txt", "w") as write_file: program
Same method works for three different data types. Thus, we cannot with correct
# to calculate area of rectangle content = read_file.read()
define two methods with the same name and same number of syntax 4M
def area(length, breadth): write_file.write(content)
arguments but having different type as shown in the above example.
calc = length * breadth 5. Attempt any TWO of the following: 12M
They will be treated as the same method. It is clear that method
print calc a) Explain basic operation performed on set with suitable example. 6M
overloading is not supported in python but that does not mean that we
#to calculate area of square Ans. In Python, sets are a built-in data structure that allows you to perform 2M for each
cannot call a method with different number of arguments. There are a a variety of operations. Python provides methods and operators to operation
def area(size):
couple of alternatives available in python that make it possible to call perform the basic set operations, such as union, intersection,
calc = size * size
the same method but with different number of arguments.erample difference, symmetric difference
print calc
method overloading
area(3) 1. Union ( | or union() )
area(4,5) c) Write a Python program to check for zero division errors 4M The union of two sets combines all elements from both sets,
Output: exception. Each removing duplicates.
9 Ans. a=int(input("Enter the value of a:")) correct A = {1, 2, 3}
TypeError: area() takes exactly 1 argument (2 given) b=int(input("Enter the value of b:")) output 1M
B = {3, 4, 5}
print( A | B) # Output: {1, 2, 3, 4, 5}
print( A.union(B)) # Output: {1, 2, 3, 4, 5}
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
Subject: Programming with Python Subject Code: 22616 Subject: Programming with Python Subject Code: 22616 Subject: Programming with Python Subject Code: 22616
Subject: Programming with Python Subject Code: 22616 Subject: Programming with Python Subject Code: 22616 Subject: Programming with Python Subject Code: 22616
print(x, type(x)) # Output: (2+3j) <class 'complex'> b) Write a Python program to read contents of first.txt file and 6M # Code that runs if no exception was raised
write same content in second.txt file. finally:
2. Sequence Types Ans. # Open the first.txt file in read mode with open('first.txt', 'r') as file1: Reading # Code that always runs (cleanup code)
Sequence types store an ordered collection of items. # Read the content of the first file contents of
first file 3M
content = file1.read() Explanation of Components
a. String (str) # Open the second.txt file in write mode (it will create the file if it try Block: Contains the code that might raise an exception.
A string is a sequence of characters enclosed within single (') or doesn't exist) except Block: Catches and handles the exception.
double (") quotes. with open('second.txt', 'w') as file2: Writing else Block: Executes if the try block succeeds without any exceptions.
# Write the content to the second file contents of finally Block: Executes regardless of whether an exception was raised
name = "John" # String
first file to
message = 'Hello, World!' file2.write(content) second file
or not. Typically used for cleanup tasks.
print(name, type(name)) # Output: John <class 'str'> print("Contents of first.txt have been copied to second.txt.") 3M
Example:
. List (list)
Explanation:
A list is an ordered, mutable collection that can contain elements of Opening first.txt: try:
any data type, including other lists. The open() function is used with the 'r' mode to open first.txt in read # Try to open and read a file
fruits = ['apple', 'banana', 'cherry'] # List mode. file = open("example.txt", "r")
print(fruits, type(fruits)) # Output: ['apple', 'banana', 'cherry'] <class with open() is used to ensure the file is properly closed after the content = file.read()
'list'> operation is complete. print(content)
Reading the contents: except FileNotFoundError:
file1.read() reads the entire content of first.txt into the variable # Handle the specific exception if the file doesn't exist
3. Mapping Type content. print("Error: The file was not found.")
Mapping types store key-value pairs. Opening second.txt: except IOError:
a. Dictionary (dict) The open() function is used with the 'w' mode to open second.txt in # Handle other I/O errors
A dictionary is an unordered, mutable collection of key-value pairs, write mode. print("Error: An IOError occurred.")
where each key is unique. If second.txt does not exist, it will be created automatically. else:
person = {'name': 'Alice', 'age': 25, 'city': 'New York'} Writing the contents: # Executes if no exceptions were raised
file2.write(content) writes the content read from first.txt into print("File was read successfully!")
print(person, type(person)) # Output: {'name': 'Alice', 'age': 25, 'city':
second.txt. finally:
'New York'} <class 'dict'> c) Explain Try-except-else-finally block used in exception handling 6M # Always executes, used to clean up resources
in Python with example. try:
4. Set Types Ans. The try-except-else-finally block is a comprehensive way to handle Each file.close()
Set types are used to store unordered collections of unique elements. exceptions in Python. It allows you to test a block of code for errors explanatio print("File has been closed.")
(try), handle the errors if they occur (except), execute code if no n ,syntax except NameError:
a. Set (set)
errors occur (else), and execute cleanup code regardless of whether an and print("File object does not exist.")
A set is an unordered collection of unique elements, and it is mutable example
(you can add or remove items). error occurred or not (finally).
2M
fruits = {'apple', 'banana', 'cherry'} # Set
print(fruits, type(fruits)) # Output: {'banana', 'apple', 'cherry'} <class try:
'set'> # Code that might raise an exceptionexcept ExceptionType:
# Code to handle the exception
else:
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
_________ _________ _________
SUMMER – 2024 EXAMINATION reverse (Optional): for reverse=True, it will sort the list descending. Default is 2. Attempt any THREE of the following: 12 M
Model Answer – Only for the Use of RAC Assessors reverse=False
key (Optional): A function to specify the sorting criteria. a) Explain with example: 4M
Subject Name: Programming with Python Subject Code:
22616 d) Write use of matplotlib package in python. 2M i) Indentation
Important Instructions to examiners:
ii) Variables
1) The answers should be examined by key words and not as word-to-word as given in the model answer scheme. Ans Use of matplotlib package in python: 1M
2) The model answer and the answer written by candidate may vary but the examiner may try to assess the 1) Matplotlib is use for creating static, animated, and interactive visualizations in Ans i) Indentation: For each
understanding level of the candidate. Python. (for each • Python provides no braces to indicate blocks of code for class and function correct
3) The language errors such as grammatical, spelling errors should not be given more Importance (Not applicable for 2) It is used along with NumPy to provide an environment that is an effective open- use of definitions or flow control. explanation
subject English and Communication Skills. matplotlib
source alternative for MATLAB. • Blocks of code are denoted by line indentation, which is compulsory. and
4) While assessing figures, examiner may give credit for principal components indicated in the figure. The figures drawn package) Example – 2
by candidate and model answer may vary. The examiner may give credit for any equivalent figure drawn.
3) Matplotlib can be used in Python scripts, the Python and IPython shell, web • The number of spaces in the indentation is variable, but all statements within
application servers, and various graphical user interface toolkits like Tkinter, the block must be indented the same amount. M
5) Credits may be given step wise for numerical problems. In some cases, the assumed constant values may vary and
there may be some difference in the candidate’s answers and model answer. awxPython, etc.
6) In case of some questions credit may be given by judgement on part of examiner of relevant answer based on
e) What is data abstruction and data hiding. 2M
candidate’s understanding.
7) For programming language papers, credit may be given to any other program based on equivalent concept.
8) As per the policy decision of Maharashtra State Government, teaching in English/Marathi and Bilingual (English + Ans Data abstraction: Data Abstraction is used to hide the internal functionality of the 1M
Marathi) medium is introduced at first year of AICTE diploma Programme from academic year 2021-2022. Hence if function from the users. The users only interact with the basic implementation of the
the students in first year (first and second semesters) write answers in Marathi or bilingual language (English function, but inner working is hidden. User is familiar with that "what function (for
+Marathi), the Examiner shall consider the same and assess the answer based on matching of concepts with model does" but they don't know "how it does." definition of
answer. data
Data hiding: Data hiding is a concept which underlines the hiding of data or information abstraction Figure of Indentation
Q. Sub Answer Marking from the user. Data hiding is a software development technique specifically used in and data • Example:
No. Q. Scheme Object-Oriented Programming (OOP) to hide internal object details (data members). hiding)
if True:
N. Data hiding includes a process of combining the data and functions into a single unit to print "True"
conceal data within a class by restricting direct access to the data from outside the class. else:
1 Attempt any FIVE of the following: 10 M print "False"
a) Enlist any four data structures used in python. 2M
f) Write the syntax of fopen. 2M • Thus, in Python all the continuous lines indented with same number of spaces
would form a block.
Ans Syntax of fopen: 2 M for ii) Variables:
Ans Data structures used in python are: 2M
1) List (Any 4
f=open(filename, mode) correct • Python Variable is containers that store values.
2) Set correct data
Were, syntax • We do not need to declare variables before using them or declare their type.
3) Tuple structures
filename: This parameter as the name suggests, is the name of the file that we want to • A variable is created the moment we first assign a value to it.
open. • A Python variable is a name given to a memory location.
4) Dictionary name)
5) Frozen Sets mode: This parameter is a string that is used to specify the mode in which the file is to be • It is the basic unit of storage in a program.
b) Give membership operators in python. 2M opened. • Variable Naming Rules in Python
1) Variable name should start with letter(a-z ,A-Z) or underscore (_).
Ans Membership operators are: 1M g) What is dictionary? 2M
Example: age, _age, Age
In: Give result true if value is found in list or in sequence, and give result false if item is 2) In variable name, no special characters allowed other than underscore (_).
not in list or in sequence (for each Ans Dictionary is an unordered collection of key-value pairs. 2 M for
Membership Example: age_, _age
Not in: Give result true if value is not found in list or in sequence, and give result false if OR correct 3) Variables are case sensitive.
item is in list or in sequence. Operators) In Python, dictionaries are mutable data structures that allow you to store key-value pairs. explanation Example: age and Age are different, since variable names are case
Dictionary can be created using the dict() constructor or curly braces' {}'. of sensitive.
c) Write syntax for a method to sort a list. 2M
dictionary 4) Variable name can have numbers but not at the beginning.
Ans Syntax of sort method for a list: 2 M for Example: Age1
list.sort(reverse=True|False, key=myFunc) correct 5) Variable name should not be a Python reserved keyword.
Were, syntax • Example:
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
_________ _________ _________
Output: 12321 is a palindrome. • A tuple data type in python programming is similar to a list data type, which also The implication of iterations is The implication of iterations is correct
2
contains heterogeneous items/elements. Time-consuming comparatively Faster points.
c) Write a python program to create a user defined module that will ask your 4M
program name and display the name of the program. Example: For tuple. The list is better for performing
A Tuple data type is appropriate for
3 operations, such as insertion and
a=(10,'abc',1+3j) accessing the elements
Ans User Defined Module- ProgramName.py 4 M for deletion.
correct
def pName(str): print(a) Tuple consumes less memory as
program. 4 Lists consume more memory
(10, 'abc', (1+3j)) compared to the list
print("Name of program is : ",str)
Example 2:List Data Type Tuple does not have many built-in
5 Lists have several built-in methods
methods.
Main program- Program.py List is an ordered sequence of items. It is one of the most used datatype in Python and is
very flexible. Unexpected changes and errors are Because tuples don’t change they are
6
import ProgramName more likely to occur far less error-prone.
• List can contain heterogeneous values such as integers, floats, strings, tuples, lists and
str=input("Enter program name: ") dictionaries but they are commonly used to store collections of homogeneous objects. Syntax: Enclosed in Square ([])
7 Syntax: Enclosed in Square (()) bracket
bracket
ProgramName.pName(str) • The list datatype in Python programming is just like an array that can store a group of
elements and we can refer to these elements using a single name. Example: Example:
Output- 8
• Declaring a list is pretty straight forward. Items separated by commas ( , ) are enclosed Employee = [‘A’, ‘B’, ‘C’] Employee = (1001, 1002, 1003)
Enter program name: Program within brackets [ ].
b) Write a python program takes in a number and find the sum of digits in a 4M
Name of program is : Program Example: number.
d) List data types used in python. Explain any two with example. 4M For list. Ans Number = int(input("Please Enter any Number: ")) 4 M for
correct
Ans Python has various standard data types that are used to define the operations possible on 2 M for first=[10, 20, 30] Sum = 0 program.
them and the storage method for each of them. Data types in Python programming types,
includes: # homogenous values in list while(Number > 0):
2 M for two
1. Numbers: Represents numeric data to perform mathematical operations. second=["One","Two","Three"] Reminder = Number % 10
proper
2. String: Represents text characters, special symbols or alphanumeric data. examples Print(first) Sum = Sum + Reminder
3. List: Represents sequential data that the programmer wishes to sort, merge etc. [10, 20, 30] Number = Number //10
4. Tuple: Represents sequential data with a little difference from list. Print(second) print("\n Sum of the digits of Given Number = %d" %Sum)
5. Dictionary: Represents a collection of data that associate a unique key with each value. ['One', 'Two', 'Three'] Output:
6. Boolean: Represents truth values (true or false). Please Enter any Number: 12
Example1: Tuple Data Type 4. Attempt any THREE of the following: 12 M Sum of the digits of Given Number = 3
• Tuple is an ordered sequence of items same as list. The only difference is that tuples are a) Compare list and tuple (any four points). 4M c) Write a program function that accepts a string and calculate the number of 4M
immutable. Tuples once created cannot be modified. uppercase letters and lower case letters.
Ans Sno. LIST TUPLE 1 M each
• Tuples are used to write-protect data and are usually faster than list as it cannot change for one Ans Str=input("Enter a String -: ") 4 M for
dynamically. It is defined within parentheses ( ) where items are separated by commas ( , 1 Lists are mutable Tuples are immutable point. def upperlower(Str): correct
). 4 M for 4 lower=0 program.
upper=0
for i in Str:
Page No: 7 | 19 Page No: 8 | 19 Page No: 9 | 19
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
_________ _________ _________
if(i.islower()): Example:
lower+=1
elif(i.isupper()): def set_data(self, rollno): Open a file and print the content:
upper+=1 self.rollno = rollno
print("The number of lowercase characters is:",lower) f = open("demofile.txt", "r")
print("The number of uppercase characters is:",upper) print(f.read())
def display_data(self):
upperlower(Str)
print(f"Roll No: {self.rollno}") ii) The write() function
student1 = Student(10)
Output - The write() method writes a specified text to the file.
Enter a String -: Welcome to Python programing student1.display_data()
The number of lowercase characters is: 23 Where the specified text will be inserted depends on the file mode and stream position.
The number of uppercase characters is: 2
"a": The text will be inserted at the current file stream position, default at the end of the
Output: file.
or
Rollno = 10
"w": The file will be emptied before the text will be inserted at the current file stream
string = input("Enter a String -: ") e) Explain following functions with example: 4M position, default 0.
def upperlower(string):
upper = 0 i) The open() function Syntax:
lower = 0
ii) The write() function file.write(byte)
for i in range(len(string)):
# For lower letters byte: The text or byte object that will be inserted.
Ans i) The open() function 2 M each
if (ord(string[i]) >= 97 and ord(string[i]) <= 122): #ord() function is used to convert
for one
a single Unicode character into its integer representation The open() function opens a file and returns it as a file object. Example:
point and
lower += 1 Open the file with "a" for appending, then add some text to the file:
Syntax: proper
# For upper letters
explanation f = open("demofile2.txt", "a")
elif (ord(string[i]) >= 65 and ord(string[i]) <= 90):
open(file, mode) with f.write("Hi!")
upper += 1
example. f.close()
file: The path and name of the file
print('Lower case characters = %s' %lower, '\nUpper case characters = %s' %upper)
mode: A string, define which mode you want to open the file in: #open and read the file after the appending:
upperlower(string) f = open("demofile2.txt", "r")
"r" - Read - Default value. Opens a file for reading, error if the file does not exist print(f.read())
Output-
"a" - Append - Opens a file for appending, creates the file if it does not exist
Enter a String -: Welcome to Python programming
Lower case characters = 24 "w" - Write - Opens a file for writing, creates the file if it does not exist 5. Attempt any TWO of the following: 12 M
Upper case characters = 2
"x" - Create - Creates the specified file, returns an error if the file exist a) Write the output for the following if the variable course = "Python" 6M
d) Write a python program to create class student with roll-no. and display its 4M
contents. In addition you can specify if the file should be handled as binary or text mode >>> course [ : 3 ]
Ans class Student: 4 M for "t" - Text - Default value. Text mode >>> course [ 3 : ]
correct "b" - Binary - Binary mode (e.g. images)
def init (self, rollno): program. >>> course [ 2 : 2 ]
self.rollno = rollno >>> course [:]
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
_________ _________ _________
>>> course [-1] CO diploma" and "I am with IF diploma' respectively. Call the method by Ans Multiple inheritance is a feature in object-oriented programming where a class can 2 M-
creating an object of each of the three classes. inherit attributes and methods from more than one parent class. This allows a class to Explanation,
>>> course [1] 4 M-any
combine and reuse code from multiple classes, promoting code reuse and modular
Ans class Diploma: 6 M - Any suitable
Ans >>>course[:3] 1 M for design.
correct logic example
each one def getdiploma(self): program
Ans: Pyt question In Python, you can achieve multiple inheritance by specifying multiple parent classes in
print("I got diploma") the definition of a child class.
course[3:]
Program:
Ans: hon
class CO(Diploma): class Person:
>>>course[2:2]
def getdiploma(self): def init (self, name, age):
Ans: a slice starting and ending at the same index, which results in an empty string. Slicing
in this way doesn't include any characters between the specified indices. print("I am with CO diploma") self.name = name
>>> course[1]
b) Write a python program to generate five random integers between 10 and 50 6M diploma_obj = Diploma() def init (self, employee_id, position):
using numpy library.
co_obj = CO() self.employee_id = employee_id
Ans import numpy as np 6 M- Any
if_obj = IF() self.position = position
correct logic
random_integer = np.random.randint(10, 51) program
self.message = message • Example: open('file.txt', 'w') • Attempting to write to a file opened in read mode will raise an error.
• Opens the file for writing. If the file doesn't exist, it creates a new file. • This mode is used when you want to write data to a file.
• If the file already exists, it appends data to the end of the file. • If the file already exists, opening it in write mode will truncate the file to
def check_password(input_password): zero length, effectively deleting its contents.
• Example: open('file.txt', 'a')
correct_password = "SecurePassword123" # Replace with the actual correct password • If the file doesn't exist, Python will create a new file.
4. Binary Mode ('b'):
• It's commonly used for tasks like writing output to a file, logging data, or
• Opens the file in binary mode. It's used in conjunction with other modes creating new files.
if input_password != correct_password: like read ('rb'), write ('wb'), or append ('ab') to deal with binary files like
images, executables, etc. 3. Append Mode ('a'):
raise InvalidPasswordException("The password you entered is incorrect.")
• Example: open('image.jpg', 'rb') • Append mode is similar to write mode but instead of truncating the file, it
else: appends data to the end of the file.
5. Text Mode ('t'):
• If the file doesn't exist, it creates a new file.
Page No: 19 | 19