(22616) PWP Summer-2022 Answer Paper
(22616) PWP Summer-2022 Answer Paper
Subject Name: Programming with Python Model Answer Subject Code: 22616
Page 1 of 23
The List has the variable The tuple has the fixed length
length
List operations are more error Tuples operations are safe
prone.
Lists can be used to store Tuples are used to store only
homogeneous and heterogeneous elements.
heterogeneous elements.
List is useful for insertion and Tuple is useful for readonly
deletion operations. operations like accessing
elements.
List iteration is slower and is Tuple iteration is faster.
time consuming.
d) Explain Local and Global variable 2M (1m each)
Local Variables: Local variables are those which are initialized
inside a function and belongs only to that particular function. It
cannot be accessed anywhere outside the function
1 Example:
def f():
# local variable
s = "I love Python Programming"
print(s)
# Driver code
f()
Output
I love Python Programming
Global Variables: The global variables are those which are defined
outside any function and which are accessible throughout the
program i.e. inside and outside of every function.
Example:
# This function uses global variable s
def f():
print("Inside Function", s)
# Global scope
s = "I love Python Programming"
f()
print("Outside Function", s)
Output:
Inside Function I love Python Programming
Outside Function I love Python Programming
e) Define class and object in python 2M (Any suitable
Class: A class is a user-defined blueprint or prototype from which definition: 1M
objects are created. Classes provide a means of bundling data Each)
and functionality together.
5 Object: An object is an instance of a class that has some
attributes and behavior. Objects can be used to access the
attributes of the class.
Page 2 of 23
f) How to give single and multiline comment in Python 2M (1m each)
Single line comment: Single-line comments are created simply by
beginning a line with the hash (#) character, and they are
automatically terminated by the end of line.
Example:
1 # print is a statement
print(‘Hello Python’)
for i in range(1,5):
for j in range(1,i+1):
print(j,end=' ')
print()
b) Explain four Buit-in tuple functions in python with example 4M ( 1M for each
function with
example)
Page 3 of 23
3
c) Explain how to use user defined function in python with example 4M (2m for
• In Python, def keyword is used to declare user defined explanation and
functions. 2m for example)
• The function name with parentheses (), which may or may
not include parameters and arguments and a colon:
• An indented block of statements follows the function
4 name and arguments which contains the body of the
function.
Syntax:
def function_name():
statements
.
.
Example:
def fun():
print(“User defined function”)
fun()
output:
User defined function
Page 4 of 23
statements
.
.
Example:
def square( x ):
print("Square=",x*x)
# Driver code
square(2)
Output:
Square= 4
d) Write a program to create class EMPLOYEE with ID and NAME 4M (for correct
and display its contents. program and
class employee : logic)
id=0
name=""
def getdata(self,id,name):
self.id=id
5 self.name=name
def showdata(self):
print("ID :", self.id)
print("Name :", self.name)
e = employee()
e.getdata(11,"Vijay")
e.showdata()
Output:
ID : 11
Name : Vijay
3 Attempt any THREE of the following 12
a) List data types used in Python. Explain any two with 4M (2m for list,
example and 2m for two
Data types in Python programming includes: example)
• Numbers: Represents numeric data to perform
mathematical operations.
• String: Represents text characters, special symbols or
alphanumeric data.
• List: Represents sequential data that the programmer
1 wishes to sort, merge etc.
• Tuple: Represents sequential data with a little
difference from list.
• Dictionary: Represents a collection of data that
associate a unique key with each value.
• Boolean: Represents truth values (true or false).
Page 5 of 23
Example: For number data types are integers.
>>>a=10
>>>b -10
To determine the type of a variable type() function is used.
>>>type(a)
>>> <class 'int'>
Page 6 of 23
>>> s1="Hello" #string in double quotes
>>> s2='Hi' #string in single quotes
>>> s3="Don't open the door" #single quote string in double
quotes
>>> s4='I said "yipee"' #double quote string in single quotes
>>>type(s1)
<class 'str'>
Page 7 of 23
8. Dictionary: Dictionary is an unordered collection of key-
value pairs. It is the same as the hash table type. The order
of elements in a dictionary is undefined, but we can iterate
over the following:
o The key
o The value
o The items (key-value pairs) in a dictionary.
When we have the large amount of data, the dictionary data
type is used. Items in 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 braces ([]).
Example: For dictionary data type.
>>> dic1={1:"First","Second":2}
>>> dic1
{1: 'First', 'Second': 2}
>>> type(dic1)
<class 'dict'>
>>> dic1[3]="Third"
>>> dic1
{1: 'First', 'Second': 2, 3: 'Third'}
>>> dic1.keys()
dict_keys([1, 'Second', 3])
>>> dic1.values()
dict_values(['First', 2, 'Third'])
>>>
b) Explain membership and assignment operators with 4M: 2m for
example membership
Membership Operators: The membership operators in Python are operators and
used to find the existence of a particular element in the sequence, 2m for
and used only with sequences like string, tuple, list, dictionary etc. assignment
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
2 reduces the effort of searching an element in the list. Python
provides ‘in’ and ‘not in’ operators which are called membership
operators and used to test whether a value or variable is in a
sequence.
Sr. Operator Description Example
No
1 in True if value is >>> x="Hello
found in list or in World"
sequence, and false >>> print('H' in x)
it item is not in list True
or in sequence
2 not in True if value is not >>> x="Hello
found in list or in World"
sequence, and false
Page 8 of 23
it item is in list or in >>> print("Hello"
sequence. not in x)
False
Page 9 of 23
c=c%a
7 **= Performs exponential c **= a is
(power) calculation on equivalent to
operators and assign
value to the left operand. c = c ** a
c) Explain indexing and slicing in list with example 4M: (2m for
Indexing: An individual item in the list can be referenced by indexing and 2m
using an index, which is an integer number that indicates the for slicing)
relative position of the item in the list.
There are various ways in which we can access the elements
of a list some as them are given below:
1. List Index: We can use the index operator [] to access an
item in a list. Index starts from 0. So, a list having 5 elements
3 will have index from 0 to 4.
Example: For list index in list.
>>> list1=[10,20,30,40,50]
>>> list1[0]
10
>>> list1[3:] # list[m:] will return elements indexed from mth
index to last index
[40, 50]
>>>list1[:4] # list[:n] will return elements indexed from first
index to n-1th index
[10, 20, 30, 40]
>>> list1[1:3] # list[m:n] will return elements indexed from m
to n-1.
[20, 30]
>>> list1[5]
Traceback (most recent call last):
File "<pyshell#71>", line 1, in <module>
list1[5]
IndexError: list index out of range
2. Negative Indexing: Python allows negative indexing for its
sequences. The index of −1 refers to the last item, −2 to the
second last item and so on.
Example: For negative indexing in list.
>>> list2=['p','y','t','h','o','n']
>>> list2[-1]
'n'
>>> list2[-6]
'p'
>>> list2[-3:]
Page 10 of 23
['h', 'o', 'n']
>>> list2[-7]
Traceback (most recent call last):
File "<pyshell#76>", line 1, in <module>
list2[-7]
IndexError: list index out of range
operation.py:
import calculation
print(calculation.add(1,2))
print(calculation.sub(4,2))
Output:
3
2
Page 11 of 23
Ans:
1)
>>> dict1={1:"Vijay",2:"Santosh",3:"Yogita"}
>>>print(dict1)
{1: 'Vijay', 2: 'Santosh', 3: 'Yogita'}
ii)
>>>dict1[2]="Shreyas"
>>>print(dict1)
{1: 'Vijay', 2: 'Shreyas', 3: 'Yogita'}
iii)
>>>dict1.pop(1)
‘Vijay'
>>>print(dict1)
{2: 'Shreyas', 3: 'Yogita'}
b) Explain decision making statements If-else, if-elif-else with 4M (2m for if-
example else and 2m for
The if-else statement: if statements executes when the if-elif-else)
conditions following if is true and it does nothing when the
condition is false. The if-else statement takes care of a true
as well as false condition.
2 Syntax-1: Or Syntax-2:
If condition: If condition:
Statement(s) If_Block
else: else:
Statement(s) else_Block
Example:
i=20
if(i<15):
print(" less than 15")
else:
print("greater than 15")
output:
greater than 15
Concept Diagram:
Page 12 of 23
if-elif-else (ladder) statements: Here, a user can decide among
multiple options. The if statements are executed from the top
down. As soon as one of the conditions controlling the if is true,
the statement associated with that if is executed, and the rest of
the ladder is bypassed. If none of the conditions is true, then the
final else statement will be executed.
Syntax:
if (condition-1):
statement
elif (condition-2):
statements
.
.
elif(condition-n):
statements
else:
statements
Example:
Example:
i = 20
if (i == 10):
print ("i is 10")
elif (i == 15):
print ("i is 15")
elif (i == 20):
print ("i is 20")
else:
print ("i is not present")
output:
i is 20
Concept Diagram:
Page 13 of 23
c) Explain use of format() method with example 4M (2m for use
The format() method formats the specified value(s) and insert and 2m for
them inside the string's placeholder. example)
The placeholder is defined using curly brackets: {}.
The format() method returns the formatted string.
3 Syntax
string.format(value1, value2...)
Example:
#named indexes:
>>>txt1 = ("My name is {fname}, I'm {age}".format(fname =
"abc", age = 36))
>>>print(txt1)
My name is abc, I'm 36
#numbered indexes:
>>>txt2 =( "My name is {0}, I'm {1}".format("xyz",36))
>>>print(txt2)
My name is xyz, I'm 36
#empty placeholders:
>>>txt3 = ("My name is {}, I'm {}".format("pqr",36))
>>>print(txt3)
My name is pqr, I'm 36
d) Explain building blocks of python 4M
Character set: All characters that python can recognize. The
below table illustrates the Python character set along with
examples.
character Set Examples
1 Letters: Upper case and
lower case english
A-Z,a-z
alphabets
Digits: all digits 0-9
Special symbols space,+,-,**,*,%,//,/,==,!=,>,<
Whitespaces Blank space,tabs
Other unicode characters All ASCII and Unicode characters
Tokens: Tokens in python are building blocks of the Python
programming language. The role letters and words play for the
English language, Similar to role token play for a python
programming language.
Python has the following tokens:
1)keywords
2)identifiers
3)literals
a)String literals
b)Numeric literals
c)Boolean Literals
d)Special literal None
Tokens Example
Keywords: Words that are False,True,if,elif,else,for,
already defined and convey a while,pass,continue,lambda,
Page 14 of 23
special meaning to the return,finally,import,def
language
compiler/interpreter
Identifiers: names given to def square,num=20,
different parts of program a_lst=[1,2,3];
like variables, functions, here square,num and a_lst are
object, class, names given to identifiers.
different datatypes.
Literals/Constants: Data String: ‘Mayank‘,’abc‘,’anish‘;
items that have fixed values Numeric: 1,1.2,4,-3.95;
Boolean: True,False
Special literal None; meaning nothing
e) Write a program illustrating use of user defined package in 4M (2m for
python defining
A package is a hierarchical file directory structure that defines a package and 2m
single Python application environment that consists of modules for import
and subpackages and sub-subpackages, and so on. package in
4 Packages allow for a hierarchical structuring of the module
namespace using dot notation.
program)
Creating a package is quite straightforward, since it makes use of
the operating system’s inherent hierarchical file structure.
Consider the following arrangement:
mod2.py
def m2():
print("second module")
Syntax-1
import <module_name>[, <module_name> ...]
Example:
>>>import pkg.mod1, pkg.mod2
>>> pkg.mod1.m1()
first module
Page 15 of 23
Syntax-2:
from <module_name> import <name(s)>
Example:
>>> from pkg.mod1 import m1
>>> m1()
First module
>>>
Syntax-3:
from <module_name> import <name> as <alt_name>
Example:
>>> from pkg.mod1 import m1 as module
>>> module()
first module
Page 16 of 23
Method overloading is a concept in which a method in a class
performs operations according to the parameters passed to
it.
As in other languages we can write a program having two
methods with same name but with different number of
arguments or order of arguments but in python if we will try
to do the same we will get the following issue with method
overloading in Python:
# to calculate area of rectangle
def area(length, breadth):
calc = length * breadth
print calc
#to calculate area of square
def area(size):
calc = size * size
print calc
area(3)
area(4,5)
Output:
9
TypeError: area() takes exactly 1 argument (2 given)
Python does not support method overloading, that is, it is
not possible to define more than one method with the
same name in a class in Python.
This is because method arguments in python do not have a
type. A method accepting one argument can be called with
an integer value, a string or a double as shown in next
example.
class Demo:
def method(self, a):
print(a)
obj= Demo()
obj.method(50)
obj.method('Meenakshi')
obj.method(100.2)
Output:
50
Meenakshi
100.2
Same method works for three different data types. Thus, we
cannot define two methods with the same name and same
number of arguments but having different type as shown in
the above example. They will be treated as the same
method.
It is clear that method overloading is not supported in python
but that does not mean that we cannot call a method with
different number of arguments. There are a couple of
Page 17 of 23
alternatives available in python that make it possible to call
the same method but with different number of arguments.
c) Write a program to open a file in write mode and append 6M for any
some content at the end of file program with
file1 = open("myfile.txt", "w") suitable logic
L = ["This is Delhi \n", "This is Paris \n", "This is London"]
file1.writelines(L)
6 file1.close()
# Append-adds at last
# append mode
file1 = open("myfile.txt", "a")
Output:
Output of Readlines after appending
This is Delhi
This is Paris
This is London
TodayTomorrow
Page 18 of 23
same type. Arrays can be made up of any number of
dimensions.
• In NumPy, dimensions are called axes. Each
dimension of an array has a length which is the total
number of elements in that direction.
• The size of an array is the total number of elements
contained in an array in all the dimension. The size of
NumPy arrays are fixed; once created it cannot be
changed again.
• Numpy arrays are great alternatives to Python Lists.
Some of the key advantages of Numpy arrays are that
they are fast, easy to work with, and give users the
opportunity to perform calculations across entire
arrays.
• A one dimensional array has one axis indicated by
Axis-0. That axis has five elements in it, so we say it
has length of five.
• A two dimensional array is made up of rows and
columns. All rows are indicated by Axis-0 and all
columns are indicated by Axis-1. If Axis-0 in two
dimensional array has three elements, so its length it
three and Axis-1 has six elements, so its length is six.
Example:
For NumPy with array object.
>>> import numpy as np
>>> a=np.array([1,2,3]) # one dimensional array
>>> print(a)
[1 2 3]
>>> arr=np.array([[1,2,3],[4,5,6]]) # two dimensional array
>>> print(arr)
[[1 2 3]
[4 5 6]]
Page 19 of 23
>>> type(arr)
<class 'numpy.ndarray'>
>>> print("No. of dimension: ", arr.ndim)
No. of dimension: 2
>>> print("Shape of array: ", arr.shape)
Shape of array: (2, 3)
>> >print("size of array: ", arr.size)
size of array: 6
>>> print("Type of elements in array: ", arr.dtype)
Type of elements in array: int32
>>> print("No of bytes:", arr.nbytes)
No of bytes: 24
b) Write a program to implement the concept of inheritance 6M for any
in python suitable
• In inheritance objects of one class procure the example of
properties of objects of another class. inheritance
• Inheritance provide code usability, which means that
some of the new features can be added to the code
5 while using the existing code.
• The mechanism of designing or constructing classes
from other classes is called inheritance.
• The new class is called derived class or child class and
the class from which this derived class has been
inherited is the base class or parent class.
• In inheritance, the child class acquires the properties
and can access all the data members and functions
defined in the parent class. A child class can also
provide its specific implementation to the functions
of the parent class.
Syntax:
class A:
# properties of class A
class B(A):
# class B inheriting property of class A
# more properties of class B
Page 20 of 23
car1.disp_price()
Output:
Name= Maruti
Price=$ 2000
Page 21 of 23
• There can be one or more except blocks. Multiple
except blocks with different exception names can be
chained together.
• The except blocks are evaluated from top to bottom
in the code, but only one except block is executed for
each exception that is thrown.
• The first except block that specifies the exact
exception name of the thrown exception 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.
• For handling exception in Python, the exception
handler block needs to be written which consists of
set of statements that need to be executed according
to raised exception. There are three blocks that are
used in the exception handling process, namely, try,
except and finally.
Syntax:
try:
D the operations here
......................
except Exception1:
If there is Exception1, then execute this block.
except Exception2:
If there is Exception2, then execute this block.
......................
else:
If there is no exception then execute this block.
Page 22 of 23
except IOError:
print ("Error: can\'t find file or read data")
else:
print ("Written content in the file successfully")
fh.close()
Page 23 of 23