b) | Write any four methods of dictionary. aM
‘Ans 4M (any four,
1M each)
Method Description
‘clear Removes allthe elements trom the lict={1"Viay2"Amar, 3 Santosh)
dictionary >>> dict
(1: Way. 2: "Amar, 3:'Santosh)
>>> dictcear)
>>> dict
o
items) | Retumsa ist containing the a tuple for | dict (7 Vay, 2 Amar, 3 Santosh]
each key value par >>> for in dicutemsQ:
print’)
0. ia")
(2Amar)
(3, ‘Santosh
red) Retumsa ist containing the Sctionary’s | dict=(1-Vjay 2Amar 3°Santosh)
keys 39> dicteys)
ict, keys1. 2,3)
7) Remaves the element with the speciied | dict=(1Vjay2°Amar 2°Santosh)
hey >>> pnintidict.popi2))
Amar
popitem) | Removes the lst inserted Key-value pay | det=(1' Vijay 2/Amar,3°Santosh]
>>> dictpopitem)
3, "Santosh)ey
‘What is focaland global variables? Explain with appropriaic example.
¢ Global variables: slobel veriables can be accessed throughout the progam
body by all functions.
© Local variables: local variables can be accessed only inside the fumction im
which they are declared
Concept Diagram:
A global variable (x) can be reached and modified anywhere in the cade, local
variable (2) cists only in Mock 2.
Example:
e-i0 global varisble g
def tesa{)}:
20 #local variable |
prnt("bocal varsibie=",f)
3 accessing global varishle
print("Giabal waruible=".2)
vs 5 MAHARASHTRA STATE BOARD OF TECH CAL EDUCATION
ia hese
== aT - Ta - Se Certified
test)
prist(" global variable="_g)
output:
focal varinblo= 21)
Global vanabie= 10
global variabic= 10Illustrate with example method over loading.
+ Method overloading is the ability to define the method with the same name but with a
different number of arguments and data types.
* With this ability one method can perform different tasks, depending on the number of
arguments or the types of the arguments given.
* Method overloading is a concept in which a method in a class performs operations
according to the parameters passed to it.def product(a, b):
p=a*b
print(p)
def product(a, 5, c):
p =a * b*¥c
print(p)
product(4, 5, 5)|Explain how try-catch block is used for exception handling in python,
+ In Python, exceptions can be handled using a try statement. A try block
consisting of one or more statements is used by programmers to partition code
that might be affected by an exception.
+ A critical operation which can raise exception is placed inside the try clause and the
code that handles exception is written in except clause.1. try Block: A set of statements that may cause error during runtime are to be written
in the try
block.
2. except Block: It is written to display the execution details to the user when certain
exception occurs in the program. The except block executed only when a certain type as
exception occurs in the execution of statements written in the try block.try:
# Some Code
except:
# Executed if error in the
# try blockExample: For try-except clause/statement.
n=10
m=0
try:
wm
except ZeroDivisionError:
print("Divide by zero error")
else:
print (n/m)
Output:
Divide by zero errorA module allows you to logically organize your Python code. Grouping related code
into a module makes the code easier to understand and use. A module is a Python
object with arbitrarily named attributes that you can bind and reference.
Simply, a module is a file consisting of Python code. A module can define functions,
classes and variables, A module can also include runnable code,Example: For creating a module. Type the following code and save it as p1.py.
def add(a, b):
"This function adds two numbers and return the result”
result = a+b
return result
def sub(a, b):
"This function subtract two numbers ani
result = a- Db
return result
\d return the result”print("division="
Addition= 3@
subtraction= -10
Multiplication= 200
division: rai| [2 a a
MAH AIASHTICA STATE BOARD OF TECHNICAL EDUCATION
‘Auannavamciss)
{ISO TEC - 27001. 2013 Certified)
Create suitable method for reading and printing students details.
class Student:
def gerStuclentDetails(self)
self.rolino=input(“Enter Roll Number < ")
selliname = input("Enter Name =“)
soll address ~impunl"Enter Address :")
def printStudentDetuils( self
phint( self rolleo.sel fname, selLaddress)
SleStudemi()
S1.getStudent Detailed)
print("Student Detars ")
Si. printSumdent 1 euils ()
Output:
Enter Roll Number : 001
Enter Name : ABC
Enter Address ; New York
Student Details
001 ABC New York
(Any suitable program can consider)Define class and object in python
Class: A class is a user-defined blueprint or prototype from which
objects are created. Classes provide a means of bundling data
and functionality together.
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.list different modes of opening file in Python
Monet for opening file:
r: open an existing file for a read operation.
® w: open an existing file for a write operation. If the file
already contains some data then it will be overridden.
* a: open an existing file for append operation. It won't
override existing data.
* r+: To read and write data into the file. The previous
data in the file will be overridden.
® w+: To write and read data. It will override existing data.
® a+: To append and read data from the file. It won't
override existing data.Explain how to use user defined function in python with example
© in Python, def keyword is used to declare user defined
functions.
® 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
name and arguments which contains the body of the
function.
def function_name():
Statements
Example:
def fun():
print(“User defined function”)
fun)
output:
User defined function
Parameterized function: The function may take arguments(s) also
called parameters as input within the opening and closing
parentheses, just after the function name followed by a colon.
)
def function_name( ‘1, astatements
Example:
def square{ x }:
print(“Square=",x*x)
# Driver code
square(2)
Output:
Square= 4Write a program for importing module for addition and
subtraction of two numbers
calculation.py:
def add(x,y):
return (x+y)
def sub(x,y):
return (x-y)
operation.py:
import calculation
print(calculation.add(1,2))
print(calculation.sub(4,2))
Output:
3
2Write a program iMustrating use of user defined package In
python
A package 6 a hierarchical file directory structure that defines a
aingle Python application environment that conaists of modules
and qubpackages and sub-subpackages, and so on.
Packages a!iow for a hierarchical structuring of the module
namespace Using dot notation.
Creating a package is quite straightforward, since A makes wpe of
the operating system's inherent hierarchical file structure.
Consider the following arrangement
By pws
Bot
se pyr
Here. there 4 a directory named pkg that contains ho
modules, mod]. py and mod?. py. The contents of the moduies
are:
modl.py
def mi}:
prieet[ “First mmodhale™)
mod2.py
def m2{}:
print{Secend module")ithe peo dinectory reugien ins iecaten where it can te found, you
can refer to the hw mmupghubes vert chet
fotation|nks.=sdi,pag.ecct]) and import them with tho
syinvtan:
Syrian.
import
]. _.|‘Syritan-2:
from module name> import-crame|s)>
thample
>> from pig nod] import mi
2>> milf)
Airst module
BSS
‘Syntaw-d:
from hare? import cname> ab calt_nae>
xample
ooo from pig. Mod. import Mm). at module
oe3 module()
first module:
{Ou Cana Ort POtune wah TheLe LterRentT aa veel:
fram import _|
from import a3
ample
=> fren ping import emnetd
ooo mod Limi)
First moduWrite a program to open a file in write mode and append
some content at the end of file
filet. = open("myfile.txt", “w")
L= [*This is Delhi \n", "This is Paris \n", “This is London")
file weitetines(L)
file1.close()
# Append-adds at last
# append mode
filel = open("myfile.txt”, a")
# writing newline character
filet.write("\n")
file. .write(“Today”)
# without newline character
file 1 .write("Tomorrow”)
file = open("myfile.txt", "r")
print("Output of Readlines after appending")
print(filet.read())
pant()
file1_close{)Output:
Output of Readlines otter: appending
This is Dethi
This is Paris
This is London
T ‘TomorrowWrite a program to implement the concept of inheritance
in python
In inheritance objects of one class procure the
properties of objects of another class.
inheritance provide code usability, which means that
some of the new features can be added to the code
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 BA):
# class B inheriting property of class A
# more properties of class B
Example 1: Inheritance without using constructor.
class Vehicle: lparent class
name="Maruti”
def display(self}:
print("Name= ",self.name)
class Category(Vehicle): itderived class
price=2000
def disp_price{self):
print("Price=$"self.price)
cari=Category()
carldisplay()) eeeses—(i‘“‘“‘“‘iai‘eOverriding
Overriding is the ability of a class to change the implementation of a method provided by one ¢
base class. Method overriding is thus a strict part of the inheritance mechanism.
* To override a method in the base class, ‘we must define a new method with same name and
parameters in the derived class,
* Overriding is a very important part of OOP since it is the feature that makes inheritance exploit its
full power. Through method overriding a class may “copy” another class, avoiding duplicated code,
and at the same time enhance or customize part of it.
Example 1: For method overriding. deb product (a,5)%
class A: # parent class praxb
“parent Class" ideeD
def display(self): ren )
print (‘This is base class.") def product La yb
class B(A): #derived class
"Child/Derived class"
def display(self):
print (‘This is derived class.")
obj = 8() # instance of child
obj.display() # child calls overridden method
Output:
This is derived class -‘Example: For data hiding.
class Counter:
_ _secretcount = @ #private variable
~deF Count (self): public method
sIF._ _secretCount += 1
print ("count=",self._ _secretCount) # accessible in the same class
cl Counter()
c1.count() #invoke method
¢1.count()
print ("Total count=",c1._ _secretCount) #cannot access private variable directly
Output:
count= 1
count= 2
AttibuteEnron: ‘Counter’ object has no attribute ‘_ _secretCount”