0% found this document useful (0 votes)
14 views

Python W22

The document outlines the examination instructions and model answers for the Programming with Python subject for the Winter 2022 examination by the Maharashtra State Board of Technical Education. It includes guidelines for examiners on assessing student responses based on understanding rather than exact wording, as well as various programming concepts and examples related to Python. Key topics covered include tuples, lambda functions, file operations, comparison operators, and exception handling.

Uploaded by

Technical AG
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Python W22

The document outlines the examination instructions and model answers for the Programming with Python subject for the Winter 2022 examination by the Maharashtra State Board of Technical Education. It includes guidelines for examiners on assessing student responses based on understanding rather than exact wording, as well as various programming concepts and examples related to Python. Key topics covered include tuples, lambda functions, file operations, comparison operators, and exception handling.

Uploaded by

Technical AG
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

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

(Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________
WINTER – 2022 EXAMINATION != Not Equal to
Subject Name: Programming with Python Model Answer Subject Code: 22616 < Less than
> Greater than
Important Instructions to examiners: XXXXX <= Less than and Equal to
1) The answers should be examined by key words and not as word-to-word as given in the model answer scheme.
>= Greater than and Equal to
2) The model answer and the answer written by candidate may vary but the examiner may try to assess the
c) Describe Tuples in Python. 2M
understanding level of the candidate.
3) The language errors such as grammatical, spelling errors should not be given more Importance (Not applicable for Ans A tuple is a collection of items which is ordered and unchangeable. 2M for
subject English and Communication Skills. Tuples are the sequence or series values of different types separated by commas (,). Definition.
4) While assessing figures, examiner may give credit for principal components indicated in the figure. The figures Example: tup1=(10,20,30)
drawn by candidate and model answer may vary. The examiner may give credit for any equivalent figure drawn.
5) Credits may be given step wise for numerical problems. In some cases, the assumed constant values may vary and d) Write use of lambda function in python. 2M
there may be some difference in the candidate’s answers and model answer.
6) In case of some questions credit may be given by judgement on part of examiner of relevant answer based on Ans The lambda function, which is also called anonymous function. A lambda function can 2M for use
candidate’s understanding. take any number of arguments, but can only have one expression.
7) For programming language papers, credit may be given to any other program based on equivalent concept. Syntax: lambda arguments : expression
8) As per the policy decision of Maharashtra State Government, teaching in English/Marathi and Bilingual (English + Example: x= lambda a,b : a*b
Marathi) medium is introduced at first year of AICTE diploma Programme from academic year 2021-2022. Hence if Print(x(10,5)
the students in first year (first and second semesters) write answers in Marathi or bilingual language (English
Output: 50
+Marathi), the Examiner shall consider the same and assess the answer based on matching of concepts with
model answer. e) Write syntax of defining class in Python. 2M

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


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

f) List file operations in Python. 2M


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

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

Operator Meaning www.diplomachakhazana.in


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

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

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

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

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

Ans i = 20 4M (for correct


if (i == 10): program and
print ("i is 10") logic)
elif (i == 15):
print ("i is 15")
elif (i == 20):
print ("i is 20")
else:
print ("i is not present")

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

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

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


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

a) Compare list and dictionary. (Any 4 points) 4M Ans import collections Any proper
import pprint logic program
Ans List Dictionary Any four point, file_input = input('File Name: ') 4M

List is a collection of index values pairs Dictionary is a hashed structure of 1 M for 1 point with open(file_input, 'r') as info:
as that of array in c++. key and value pairs. count = collections.Counter(info.read().upper())
value = pprint.pformat(count)
List is created by placing elements in [ ] Dictionary is created by placing print(value)
separated by commas “, “ elements in { } as “key”:”value”,
each key value pair is separated by d) Write python program to read contents of abc.txt and write same content to 4M
commas “, “ pqr.txt.

The indices of list are integers starting The keys of dictionary can be of any Ans with open('abs.txt','r') as firstfile, open('prq.txt','w') as secondfile: Any proper
from 0. data type. # read content from first file logic program
for line in firstfile: for 4 M
The elements are accessed via indices. The elements are accessed via key- # write content to second file
values. secondfile.write(line)
The order of the elements entered are There is no guarantee for
maintained. maintaining order.
5. Attempt any TWO of the following: 12 M
b) What is command line argument? Write python code to add b) two 4M
a) Write different data types in python with suitable example. 6M
numbers given as input from command line arguments and print its sum.
Ans Data types in Python programming includes:
 Numbers: Represents numeric data to perform mathematical operations.
Page No: 11 | 21 Page No: 12 | 21
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2013 Certified) (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________ __________________________________________________________________________________________________
 String: Represents text characters, special symbols or alphanumeric data. 5. String Data Type: String is a collection of group of characters. Strings are identified
 List: Represents sequential data that the programmer wishes to sort, merge etc. as a contiguous set of characters enclosed in single quotes (' ') or double quotes (" ").
6m for data
 Tuple: Represents sequential data with a little difference from list. types
Any letter, a number or a symbol could be a part of the string. Strings are
 Dictionary: Represents a collection of data that associate a unique key with each unchangeable (immutable). Once a string is created, it cannot be modified.
value. Example: For string data type.
 Boolean: Represents truth-values (true or false). >>> s1="Hello" #string in double quotes
>>> s2='Hi' #string in single quotes
1. Integers (int Data Type): An integer is a whole number that can be positive (+) or >>> s3="Don't open the door" #single quote string in double quotes
negative (−). Integers can be of any length, it is only limited by the memory available. >>> s4='I said "yipee"' #double quote string in single quotes
Example: For number data types are integers. >>>type(s1)
>>>a=10 <class 'str'>
>>>b -10
To determine the type of a variable type() function is used. 6. List Data Type: List is an ordered sequence of items. It is one of the most used
>>>type(a) datatype in Python and is very flexible.
>>> <class 'int'> List can contain heterogeneous values such as integers, floats, strings, tuples, lists and
dictionaries but they are commonly used to store collections of homogeneous objects.
2. Boolean (Bool Data Type: The simplest build-in type in Python is the bool type, it The list datatype in Python programming is just like an array that can store a group of
represents the truth-values False and True. Internally the true value is represented as elements and we can refer to these elements using a single name. Declaring a list is
1 and false is 0. pretty straight forward. Items separated by commas ( , ) are enclosed within brackets [
For example ].
>>>a = 18 > 5 Example: For list.
>>>print(a) >>> first=[10, 20, 30] # homogenous values in list
True >>> second=["One","Two","Three"] # homogenous values in list
b=2>3 >>> first
print(b) [10, 20, 30]
False >>> second
['One', 'Two', 'Three']
3. Floating-Point/Float Numbers (Float Data Type): Floating-point number or Float is >>> first + second # prints the concatenated lists
a positive or negative number with a fractional part. A floating point number is [10, 20, 30, 'One', 'Two', 'Three']
accurate up to 15 decimal places. Integer and floating points are separated by decimal
points. 1 is integer, 1.0 is floating point number. 7. Tuple Data Type: Tuple is an ordered sequence of items same as list. The only
Example: Floating point number. difference is that tuples are immutable.
x=10.1 Tuples once created cannot be modified. It is defined within parentheses ( ) where
type(x) items are separated by commas ( , ).
<class 'float'> A tuple data type in python programming is similar to a list data type, which also
contains heterogeneous items/elements.
4. Complex Numbers (Complex Data Type): Complex numbers are written in the form, Example: For tuple.
x + yj, where x is the real part and y is the imaginary part. >>> a=(10,'abc',1+3j)
Example: >>> a
Complex number. (10, 'abc', (1+3j))
>>>x = 3+4j >>> a[0]
>>>print(x.real) 10
3.0 >>> a[0]=20
>>>print(x.imag) Traceback (most recent call last):
4.0 File "<pyshell#12>", line 1, in <module>

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


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

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


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

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


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

# function feed
def feed(self):
print("I eat only plants. I am vegetarian.")

herbi = Herbivorous()

herbi.feed()
# calling some other function
herbi.breathe()

Output:
I eat only plants. I am vegetarian.
I breathe oxygen.

Page No: 21 | 21

You might also like