Untitled
Untitled
Untitled
Semester– VI
(CO/CW/CM/IF)
Maharashtra State
Board of Technical Education, Mumbai
(Autonomous)(ISO:9001:2015) (ISO/IEC27001:2013)
Maharashtra State
Board of Technical Education, Mumbai
(Autonomous) (ISO:9001:2015) (ISO/IEC 27001:2013)
4th Floor, Government Polytechnic Building, 49, Kherwadi,
Bandra (East), Mumbai -400051.
(Printed on November 2019)
Maharashtra State
Board of Technical Education
Certificate
This is to certify that Mr. / Ms. ………………………………….
Roll No………………………. of Sixth Semester of Diploma in
………………………………………………………. of Institute
………………………….……………………………………......
(Code…………) has completed the term work satisfactorily in
subject Programming with Python (22616) for the academic
year 20…….to 20…...... as prescribed in the curriculum.
Seal of
the
Institute
Programming with Python (22616)
Preface
The primary focus of any engineering laboratory/field work in the technical education system
is to develop the much needed industry relevant competencies and skills. With this in view,
MSBTE embarked on this innovative ‘I’ Scheme curricula for engineering Diploma
programmes with outcome-based education as the focus and accordingly, relatively large
amount of time is allotted for the practical work. This displays the great importance of
laboratory work making each teacher, instructor and student to realize that every minute of the
laboratory time need to be effectively utilized to develop these outcomes, rather than doing
other mundane activities. Therefore, for the successful implementation of this outcome-based
curriculum, every practical has been designed to serve as a ‘vehicle’ to develop this industry
identified competency in every student. The practical skills are difficult to develop through
‘chalk and duster’ activity in the classroom situation. Accordingly, the ‘I’ scheme laboratory
manual development team designed the practical’s to focus on outcomes, rather than the
traditional age old practice of conducting practical’s to ‘verify the theory’ (which may become
a by-product along the way).
This laboratory manual is designed to help all stakeholders, especially the students, teachers
and instructors to develop in the student the pre-determined outcomes. It is expected from
each student that at least a day in advance, they have to thoroughly read the concerned
practical procedure that they will do the next day and understand minimum theoretical
background associated with the practical. Every practical in this manual begins by identifying
the competency, industry relevant skills, course outcomes and practical outcomes which serve
as a key focal point for doing the practical. Students will then become aware about the skills
they will achieve through procedure shown there and necessary precautions to be taken, which
will help them to apply in solving real-world problems in their professional life.
This manual also provides guidelines to teachers and instructors to effectively facilitate
student-centered lab activities through each practical exercise by arranging and managing
necessary resources in order that the students follow the procedures and precautions
systematically ensuring the achievement of outcomes in the students.
Although all care has been taken to check for mistakes in this laboratory manual, yet it is
impossible to claim perfection especially as this is the first edition. Any such errors and
suggestions for improvement can be brought to our notice and are highly welcome.
PO1 Basic knowledge: Apply knowledge of basic mathematics, sciences and basic
engineering to solve the broad-based Computer engineering problem.
PO2 Discipline knowledge: Apply Computer engineering discipline-specific
knowledge to solve core computer engineering related problems.
PO3 Experiments and practice: Plan to perform experiments and practices to use
the results to solve broad-based Computer engineering problems.
PO4 Engineering tools: Apply relevant Computer technologies and tools with an
understanding of the limitations.
PO5 The engineer and society: Assess societal, health, safety, legal and cultural
issues and the consequent responsibilities relevant to practice in field of
Computer engineering.
PO6 Environment and sustainability: Apply Computer engineering solutions also
for sustainable development practices in societal and environmental contexts and
demonstrate the knowledge and need for sustainable development.
PO7 Ethics: Apply ethical principles for commitment to professional ethics,
responsibilities and norms of the practice also in the field of Computer
engineering.
PO8 Individual and team work: Function effectively as a leader and team member
in diverse/ multidisciplinary teams.
PO9 Communication: Communicate effectively in oral and written form.
PO10 Life-long learning: Engage in independent and life-long learning activities in
the context of technological changes in the Computer engineering field and
allied industry.
The following industry relevant skills of the competency “Develop general purpose
programming using Python to solve problem” are expected to be developed in you by
performing practicals of this laboratory manual.
1. Develop Applications using Python.
2. Write and Execute Python programs using functions, classes and Exception handling
Student shall read the points given below for understanding the theoretical concepts and
practical applications.
1. Students shall listen carefully the lecture given by teacher about importance of
subject, learning structure, course outcomes.
2. Students shall organize the work in the group of two or three members and make a
record of all observations.
3. Students shall understand the purpose of experiment and its practical implementation.
4. Students shall write the answers of the questions during practical.
5. Student should feel free to discuss any difficulty faced during the conduct of
practical.
6. Students shall develop maintenance skills as expected by the industries.
7. Student shall attempt to develop related hands on skills and gain confidence.
8. Students shall refer technical magazines; websites related to the scope of the subjects
and update their knowledge and skills.
9. Students shall develop self-learning techniques.
10. Students should develop habit to submit the write-ups on the scheduled dates and
time.
Content Page
List of Practical’s and Progressive Assessment Sheet
elements
c) Update Dictionary
d) Delete Set
e) Looping through
Dictionary
a) Write Python program to
demonstrate math built- in
functions (Any 2 programs)
10. 61
b) Write Python program to
demonstrate string built – in
functions (Any 2 programs)
Develop user defined Python
function for given problem:
11. a) Function with minimum 2 67
arguments
b) Function returning values
Write Python program to
demonstrate use of:
a) Builtin module (e.g.
12. 73
keyword, math, number,
operator)
b) user defined module.
Write Python program to
demonstrate use of:
13. a) built-in packages (e.g. 80
NumPy, Pandas)
b) user defined packages
Write a program in Python to
demonstrate following operations:
14. 86
a) Method overloading
b) Method overriding
Write a program in Python to
demonstrate following operations:
15. 92
a) Simple inheritance
b) Multiple inheritance
Write a program in Python to
16. handle user defined exception for 98
given problem
Total Marks
Total Marks (Scaled to 25 Marks)
V. Practical Outcomes(PrOs)
Setup a Python programming development environment
• Click on next install now for installation and then Setup progress windows will be
opened as shown in Fig. 4.
• After complete the installation, Click on close button in the windows as shown in
Fig. 5.
• Click on all programs and then click on Python 3.7 (32 bit). You will see the
Python interactive prompt in Python command line.
• To exit from the command line of Python, press Ctrl+z followed by Enter or Enter
exit() or quit() and Enter.
• You will see the Python interactive prompt i.e. interactive shell.
• Python interactive shell prompt contains opening message >>>, called shell
prompt. A cursor is waiting for the command. A complete command is called a
statement. When you write a command and press enter, the Python interpreter will
immediately display the result.
Ans 2:- IDLE stands for Integrated Developing and Learning Environment. It is an integrated
development environment for python, which has been handled with the default implementation of
the language since 1.5
Ans 4:- PYTHON PATH is an environment variable which you can set to add additional
directories where python will look for modules and packages.
Ans 5:- PEP:- PEP stands for Python Enhancement Proposal is a design document that provides
information to the python community or describing a new feature for python or its processes or
environment.
PIP:- PIP is package manager for python that means it’s a tool that allows you to install and
manage additional libraries and dependencies that are not distributed as part of the standard
library.
XI. Exercise
(Use blank space for answers or attach more pages if needed)
1. Print the version of Python
2. Write steps to be followed to load Python interpreter in windows.
Ans 2:-
Step 1:- Open system properties.
Step 2:- Click on advanced system setting in the sidebar.
Step 3:- Click environment variables.
Step 4:- Select PATH in the system variable section.
Step 5:- Click on edit.
Step 6:-Apply python path to the end of the list.
Type the following text at the Python prompt and press the Enter –
>>> print "Hello, Python!"
If you are running new version of Python, then you would need to use print statement
with parenthesis as in print ("Hello, Python!"); However, in Python version 2.4.3,
this produces the following result:
Hello, Python!
Script Mode Programming
Invoking the interpreter with a script parameter begins execution of the script and
continues until the script is finished. When the script is finished, the interpreter is no
longer active.
Let us write a simple Python program in a script. Python files have extension .py.
Type the following source code in a test.py file:
print "Hello, Python!"
We assume that you have Python interpreter set in PATH variable. Now, try to run this
program as follows:
$ Python test.py
This produces the following result:
Hello, Python!
Let us try another way to execute a Python script. Here is the modified test.py file:
#!/usr/bin/Python
print "Hello, Python!"
We assume that you have Python interpreter available in /usr/bin directory. Now, try to
run this program as follows:
$ chmod +x test.py # This is to make file executable
$./test.py
This produces the following result –
Hello, Python!
Ans 2:-For workin with interactive mode open Python IDLE in interactive mode. Type your code
into prompt after >>> and press enter answer will be display.
Ans 3:- goto file-→ create new file-→ write your code -→ execute code using F5 or Run button
Ans 4:- add a shebang line to the top of the script #!/usr/bin/ env python
Mark the script executable chmod+x scriptname.py
Add the dir containing to your path variable
Export PATH=/path/to/script:$PATH
XI. Exercise
Note: Faculty must ensure that every group of students use different input value.
(Use blank space for answers or attach more pages if needed)
1. Write a Python program to display your name using Interactive Mode
2. Write a Python program to display “MSBTE” using Script Mode
(Space for answers)
Ans 1:-
>>>print("your name")
Ans 2:-
>>>print("MSBTE")
OUTPUT:-MSBTE.
V. Practical Outcomes(PrOs)
Develop Python program using operators: Arithmetic Operators, Logical Operators,
Bitwise Operators
Bitwise Operators: Bitwise operators acts on bits and performs bit by bit operation.
If a=10 (1010) and b=4 (0100)
Operator Meaning Description Example Output
& Bitwise Operator copies a bit, to the result, >>>(a&b) 0
AND if it exists in both operands
| Bitwise OR It copies a bit, if it exists in either >>>(a|b) 14
operand.
~ Bitwise It is unary and has the effect of >>>(~a) -11
NOT 'flipping' bits.
^ Bitwise It copies the bit, if it is set in one >>>(a^b) 14
XOR operand but not both.
>> Bitwise The left operand's value is moved >>>(a>>2) 2
right shift right by the number of bits
specified by the right operand.
<< Bitwise left The left operand's value is moved >>>(a<<2) 40
Example:-
a=False
b=True
print("a and b==", a and b)
print("a or b==", a or b)
print("not b==", not b)
OUTPUT:
a and b== False
a or b== True
not b== False
Ans 4:-
Operator Description
+ (Addition) It is used to add two operands. For example, if a = 20, b = 10 => a+b = 30
- (Subtraction) It is used to subtract the second operand from the first operand. If the first
operand is less than the second operand, the value results negative. For example,
if a = 20, b = 10 => a - b = 10
/ (divide) It returns the quotient after dividing the first operand by the second operand.
For example, if a = 20, b = 10 => a/b = 2.0
* It is used to multiply one operand with the other. For example, if a = 20, b = 10
(Multiplication) => a * b = 200
% (reminder) It returns the reminder after dividing the first operand by the second operand.
For example, if a = 20, b = 10 => a%b = 0
// (Floor It gives the floor value of the quotient produced by dividing the two operands.
division)
<< Zero fill left Shift left by pushing zeros in from the right and let the
shift leftmost bits fall off
>> Signed right Shift right by pushing copies of the leftmost bit in from the
shift left, and let the rightmost bits fall off
Exercise
Note: Faculty must ensure that every group of students use different input value.
(Use blank space for answers or attach more pages if needed)
1. Write a program to convert U.S. dollars to Indian rupees.
2. Write a program to convert bits to Megabytes, Gigabytes and Terabytes
3. Write a program to find the square root of a number
4. Write a program to find the area of Rectangle
5. Write a program to calculate area and perimeter of the square
6. Write a program to calculate surface volume and area of a cylinder.
7. Write a program to swap the value of two variables
(Space for answers)
Ans 1:-
usdollar=int(input("Enter Dollar amount"))
indrup=usdollar*75
print("Indian Rupee==",indrup)
OUTPUT
Enter Dollar amount 12
Indian Rupee== 900
Ans 2:-
bits=int(input("Enter number of bits"))
byte=bits/8
kb=byte/1024
mb=kb/1024
gb=mb/1024
tb=gb/1024
print("MEGABITES==",mb)
print("GIGABITES==",gb)
print("TERABITES==",tb)
OUTPUT
Enter number of bits 10
MEGABITES== 1.1920928955078125e-06
GIGABITES== 1.1641532182693481e-09
TERABITES== 1.1368683772161603e-12
Ans 3:-
a=int(input("Enter a number"))
sq=a**0.5
print("Square root of ",a,"is" ,sq)
OUTPUT
Enter a number4
Square root of 4 is 2.0
Maharashtra State Board of Technical Education 20
Programming with Python (22616)
Ans 4:-
length=int(input("Enter length="))
breadth=int(input("Enter breadth="))
print("Area==",(length*breadth))
OUTPUT
Enter length=12
Enter breadth=20
Area== 240
Ans 5:-
import math
s=int(input("Enter side=="))
print("Area==",s*s)
print("Perimeter==",(4*s))
OUTPUT
Enter side==5
Area== 25
Perimeter== 20
Ans 6:-
r=int(input("Enter Radius=="))
h=int(input("Enter Height=="))
sv=3.14*r*r*h
ac=2*3.14*r*(r+h)
print("surface area==",sv)
print("Area of cylinder=",ac)
OUTPUT
Enter Radius==2
Enter Height==4
surface area== 50.24
Area of cylinder= 75.36
Ans 7:-
no1=int(input("Enter 1st no"))
no2=int(input("Enter 2nd no"))
print("Before swapping")
print("no1=",no1)
print("no2=",no2)
temp=no1
no1=no2
no2=temp
print("After swapping")
print("no1=",no1)
print("no2=",no2)
OUTPUT
Enter 1st no12
Enter 2nd no59
Before swapping
no1= 12
no2= 59
After swapping
no1= 59
no2= 12
V. Practical Outcomes(PrOs)
Develop Python program using Conditional operators: if, if-else and Nested if
statement.
Ans 2:-
If statement Nested if statement
All conditions must be tested In nested if when a logical decision is true then
the remaining conditions are ignored
It is a simple statement It is a complex
All conditions must be tested so it is a time Statements are tested until the condition
consuming process becomes true, so it is not a time consuming
process
XI. Exercise
Note: Faculty must ensure that every group of students use different input value.
(Use blank space for answers or attach more pages if needed)
1. Write a program to check whether a number is even or odd
2. Write a program to find out absolute value of an input number
3. Write a program to check the largest number among the three numbers
4. Write a program to check if the input year is a leap year of not
5. Write a program to check if a Number is Positive, Negative or Zero
6. Write a program that takes the marks of 5 subjects and displays the grade.
OUTPUT:-
Enter number:==12
Number is Even
-----------------------------------------------------------------
Ans 2:-
no=int(input("Enter number:=="))
print("Absolute value of a number",no,"==",abs(no))
OUTPUT:-
Enter number:==-89
Absolute value of a number -89 == 89
------------------------------------------------------------------------
Ans 3:-
print("LARGEST OF THREE NUMBERS")
OUTPUT:-
--------------------------------------------------------------------------
Ans 4:-
print("LEAP YEAR")
year=int(input("Enter year:="))
if year%4==0:
if year%400==0:
if year%100==0:
print("Leap Year")
else:
print("Not Leap Year")
else:
print("LEap Year")
else:
print("Not Leap Year")
OUTPUT:-
LEAP YEAR
Enter year:=2003
Not Leap Year
--------------------------------------------------------------------------------
Ans 5:-
no=int(input("Enter number=="))
if no==0:
print("Number is zero")
elif no>0:
print("Number is Positive")
else:
print("Number is Negative")
OUTPUT:-
Ans 6:-
print("Display Grades")
print("Enter marks for 5 subjects")
c=float(input("c:="))
java=float(input("java:="))
python=float(input("python:="))
mad=float(input("mad:="))
maths=float(input("maths:="))
avg=(java+c+python+mad+maths)/5
print("AVERAGE==",avg)
if avg>=75:
print("DISTINCTION")
elif avg>=60:
print("FIRST CLASS")
elif avg>=40:
print("SECOND CLASS")
else:
print("FAIL")
OUTPUT:--
Display Grades
Enter marks for 5 subjects
c:=45
java:=85
python:=40
mad:=35
maths:=40
AVERAGE== 49.0
SECOND CLASS
V. Practical Outcomes(PrOs)
Write Python program to demonstrate use of looping statements:
• ‘while’ loop
• ‘for’ loop
• Nested loops
Ans 1:-
10
9
8
7
6
Ans 2:-
for x in range(1,10):
print(x)
x=x+1
XI. Exercise
Note: Faculty must ensure that every group of students use different input value.
(Use blank space for answers or attach more pages if needed)
1. Print the following patterns using loop:
a. *
**
***
****
b. *
***
*****
***
*
c. 1010101
10101
101
1
2. Write a Python program to print all even numbers between 1 to 100 using while
loop.
3. Write a Python program to find the sum of first 10 natural numbers using for loop.
4. Write a Python program to print Fibonacci series.
5. Write a Python program to calculate factorial of a number
6. Write a Python Program to Reverse a Given Number
7. Write a Python program takes in a number and finds the sum of digits in a
number.
8. Write a Python program that takes a number and checks whether it is a palindrome
or not.
(Space for answers)
Ans 1:-
a)
for i in range(0,4):
print("\r")
for j in range(0,i+1):
print("*",end="")
b)
n=0
rows=3
for i in range(1,rows+1):
for j in range(1,(rows-i)+1):
print(end=" ")
while n!=(2*i-1):
print("*",end="")
n=n+1
n=0
Maharashtra State Board of Technical Education 35
Programming with Python (22616)
print()
k=1
n=1
for i in range(1,rows):
for j in range(1,k+1):
print(end=" ")
k=k+1
while n<=(2*(rows-i)-1):
print("*",end="")
n=n+1
n=1
print()
c)
rows=5
k=1
n=1
num=0
for i in range(1,rows):
if(rows%2==0):
num=0
else:
num=1
for j in range(1,k+1):
print(end="")
k=k+1
while n<=(2*(rows-i)-1):
if rows%2==0:
if num==1:
print("1",end="")
n=n+1
num=0
else:
print("0",end="")
n=n+1
num=1
else:
if num==1:
print("1",end="")
n=n+1
num=0
else:
print("0",end="")
Maharashtra State Board of Technical Education 36
Programming with Python (22616)
n=n+1
num=1
n=1
print()
Ans 2:-
num=1
while num<=100:
if num%2==0:
print(num)
num=num+1
Ans 3:-
num=1
sum=0
for i in range(1,11):
sum=sum+i
print("Sum==",sum)
OUTPUT:-
Sum== 55
Ans 4:-
no=int(input("Enter range=="))
f1=0
f2=1
f3=f1+f2
if no>1:
print(f1)
print(f2)
print("FIBBO ==",no)
while f3<=no:
print(f3)
f1=f2
f2=f3
f3=f1+f2
else:
print("Enter value more than 1")
OUTPUT:-
Enter range==20
0
1
FIBBO == 20
1
2
3
5
8
13
Ans 5:-
num=int(input("Enter number"))
fact=1
print("Factorial of",num)
while num>=1:
fact=fact*num
num=num-1
print(fact)
OUTPUT:-
Enter number5
Factorial of 5
120
Ans 6:-
num=int(input("enter a number:="))
rev=0
while num!=0:
digit=int(num%10)
num=int(num/10)
rev=int(rev*10+digit)
print("REV==",rev)
OUTPUT:--
enter a number:=125
REV== 521
Maharashtra State Board of Technical Education 38
Programming with Python (22616)
Ans 7:-
num=int(input("enter a number:="))
sum=0
while num!=0:
digit=int(num%10)
num=int(num/10)
sum=int(sum+digit)
print("sum==",sum)
OUTPUT:-
enter a number:=12
sum== 3
Ans 8:--
num=int(input("enter a number:="))
rev=0
num1=num
while num!=0:
digit=int(num%10)
num=int(num/10)
rev=int(rev*10+digit)
print("REV==",rev)
if num1==rev:
print("Palindrome")
else:
print("Not PAlindrome")
OUTPUT:--
enter a number:=123
REV== 321
Not PAlindrome
I. Practical Significance
A list can be defined as a collection of values or items of different types. The items in
the list are separated with the comma (,) and enclosed with the square brackets [].
The elements or items in a list can be accessed by their positions i.e. indices. This
practical will make student acquainted with use of list and operations on list in
Python.
V. Practical Outcome(PrOs)
Develop Python program to perform following operations on Lists: Create list, Access
list Update list (Add item, Remove item) and Delete list
• The elements or items in a list can be accessed by their positions i.e. indices
• In Python lists are written with square brackets. A list is created by placing all the
items (elements) inside a square brackets [ ], separated by commas.
• Lists are mutable. The value of any element inside the list can be changed at any
point of time.
• The index always starts with 0 and ends with n-1, if the list contains n elements.
a) Creating List: Creating a list is as simple as putting different comma-separated
values between square brackets.
Example:
>>>List1=[‘Java’,’Python’,’Perl’]
>>>List2=[10,20,30,40,50]
b) Accessing List: To access values in lists, use the square brackets for slicing along
with the index or indices to obtain value available at that index.
Example:
>>>List2
[10,20,30,40,50]
>>>List2[1]
20
>>>List2[1:3]
[20,30]
>>>List2[5]
Traceback (most recent call last):
File "<pyshell#71>", line 1, in <module>
List2[5]
IndexError: list index out of range
c) Updating List: You can update single or multiple elements of lists by giving the
slice on the left-hand side of the assignment operator, and you can add to elements in a
list with the append() method.
>>>List2
[10,20,30,40,50]
>>>List2[0]=60 #Updating first item
[60,20,30,40,50]
>>>List2[3:4]=70,80
>>>[60,20,30,70,80,50]
i) We can add one item to a list using append() method or add several items using
extend() method.
>>> list1=[10,20,30]
>>> list1
[10, 20, 30]
>>> list1.append(40)
>>> list1
[10, 20, 30, 40]
>>> list1.extend([60,70])
>>> list1
[10, 20, 30, 40, 60, 70]
ii) We can also use + operator to combine two lists. This is also called
concatenation
>>> list1=[10,20,30]
>>> list1
[10, 20, 30]
>>> list1+[40,50,60]
[10, 20, 30, 40, 50, 60]
iii) The * operator repeats a list for the given number of times.
>>> list2 ['A', 'B']
>>> list2 *2
['A', 'B', 'A', 'B']
iv) We can insert one item at a desired location by using the method insert()
>>> list1
[10, 20]
>>> list1.insert(1,30)
>>> list1
[10, 30, 20]
d) Deleting List: To remove a list element, you can use either the del statement if you
know exactly which element(s) you are deleting or the remove() method if you do not
know.
i) Del Operator: We can delete one or more items from a list using the keyword del. It
can even delete the list entirely. But it does not store the value for further use.
Example:
>>> list=[10,20,30,40,50]
>>> del list[2]
>>> list
[10, 20, 40, 50]
ii) Remove Operator: We use the remove operator if we know the item that we want
to remove or delete from the list (but not the index)
Example:
>>> list=[10,20,30,40,50]
>>> list.remove(30)
>>> list
[10, 20, 40, 50]
XI. Exercise
Note: Faculty must ensure that every group of students use different input value.
(Use blank space for answers or attach more pages if needed)
1. Write a Python program to sum all the items in a list.
2. Write a Python program to multiplies all the items in a list.
3. Write a Python program to get the largest number from a list.
4. Write a Python program to get the smallest number from a list.
5. Write a Python program to reverse a list.
6. Write a Python program to find common items from two lists.
7. Write a Python program to select the even items of a list.
list=[3,6,7,2,3]
print("list==",list)
sum=0
for i in list:
sum=sum+i
print("sum==",sum)
OUTPUT:-
list== [3, 6, 7, 2, 3]
sum== 21
Ans 2:-
list=[3,6,7,2,3]
print("list==",list)
mul=1
for i in list:
mul=mul*i
print("mul==",mul)
OUTPUT:--
list== [3, 6, 7, 2, 3]
mul== 756
Ans 3:-
list=[3,6,7,2,3]
print("list==",list)
print("Largest==",max(list))
OUTPUT:--
list== [3, 6, 7, 2, 3]
Largest== 7
Ans 4:--
list=[3,6,7,2,3]
print("list==",list)
print("Smallest==",min(list))
OUTPUT:--
list== [3, 6, 7, 2, 3]
Smallest== 2
Ans 5:-
list=[3,6,7,2,3]
print("list==",list)
list.reverse()
print("REverse==",list)
OUTPUT:--
list== [3, 6, 7, 2, 3]
REverse== [3, 2, 7, 6, 3]
Ans 6:--
list1=[1,2,3,4]
list2=[1,2,6,7,8]
print("List1==",list1)
print("List2==",list2)
print("Common elements==",set(list1)&set(list2))
OUTPUT:--
List1== [1, 2, 3, 4]
List2== [1, 2, 6, 7, 8]
Common elements== {1, 2}
Ans 7:--
list1=[1,2,3,4,8,33,24]
print("List==",list1)
print("Even numbers==")
for i in list1:
if i%2==0:
print(i)
OUTPUT:--
I. Practical Significance
Like list python supports new tuple as a distinct structure. Tuple are use to store
sequence of python objects which are static in nature. A tuple is immutable which
means it cannot be changed. Just like a list, a tuple contains a sequence of objects in
order but once created a tuple, it cannot be changed anything about it.
V. Practical Outcome(PrOs)
Write Python program to perform following operations on Tuples:
1. Create Tuple
2. Access Tuple
3. Update Tuple
4. Delete Tuple
Example
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d";
The empty tuple is written as two parentheses containing nothing
tup1 = ();
To write a tuple containing a single value you have to include a comma, even though
there is only one value.
tup1 = (50,);
Like string indices, tuple indices start at 0, and they can be sliced, concatenated, and so
on.
b) Accessing Values in Tuples
To access values in tuple, use the square brackets for slicing along with the index or
indices to obtain value available at that index.
Example:
#!/usr/bin/Python
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5, 6, 7 );
print "tup1[0]: ", tup1[0];
print "tup2[1:5]: ", tup2[1:5];
Output:
tup1[0]: physics
tup2[1:5]: [2, 3, 4, 5]
c) Updating Tuples: Tuples are immutable which means you cannot update or change
the values of tuple elements. You are able to take portions of existing tuples to create
new tuples.
Example:
#!/usr/bin/Python
tup1 = (12, 34.56);
tup2 = ('abc', 'xyz');
# Following action is not valid for tuples
# tup1[0] = 100;
# So let's create a new tuple as follows
tup3 = tup1 + tup2;
print tup3;
Output:
(12, 34.56, 'abc', 'xyz')
d) Delete Tuple Elements: Removing individual tuple elements is not possible. There
is, of course, nothing wrong with putting together another tuple with the undesired
elements discarded. To explicitly remove an entire tuple, just use the del statement.
Example:
#!/usr/bin/Python
tup = ('physics', 'chemistry', 1997, 2000);
print tup;
del tup;
Ans 3:-
List Tuple
Lists are mutable Tuples are immutable
Implementation of iteration are time consuming Implications of iteration is faster
It is best for performing operations such as It is appropriate for accessing the elements
insertion and deletion
It consumes more memory It consumes less memory
XI. Exercise
Note: Faculty must ensure that every group of students use different input value.
(Use blank space for answers or attach more pages if needed)
1. Create a tuple and find the minimum and maximum number from it.
2. Write a Python program to find the repeated items of a tuple.
3. Print the number in words for Example: 1234 => One Two Three Four
OUTPUT:--
Tuple== (1, 2, 5, 7, 3, 9)
MAX== 9
MIN== 1
Ans 2:--
t=(1,2,5,7,3,9,2,7,1)
print("Tuple==",t)
count=t.count(1)
print(count)
OUTPUT:--
Tuple== (1, 2, 5, 7, 3, 9, 2, 7, 1)
2
Ans 3:--
t=("one","two","three","four","five","six","seven","eight","nine","ten")
print("Number in words")
i=int(input("Enter number=="))
if i==1:
print(t[0])
if i==2:
print(t[1])
if i==3:
print(t[2])
if i==4:
print(t[3])
if i==5:
print(t[4])
if i==6:
print(t[5])
if i==7:
print(t[6])
if i==8:
print(t[7])
if i==9:
print(t[8])
if i==10:
print(t[9])
OUTPUT:--
Number in words
Enter number==5
five
V. Practical Outcome(PrOs)
Develop Python program to perform following operations on Sets: Create, Access,
Update and Delete set
• The elements in the set are immutable (cannot be modified) but the set as a whole
is mutable.
• There is no index attached to any element in a Python set. So they do not support
any indexing or slicing operation.
The sets in Python are typically used for mathematical operations like union,
intersection, difference and complement etc.
a) Creating a set:
A set is created by using the set() function or placing all the elements within a pair of
curly braces.
Example:
>>> a={1,3,5,4,2}
>>> print("a=",a)
a= {1, 2, 3, 4, 5}
>>> print(type(a))
<class 'set'>
b) Accessing values in a set: We cannot access individual values in a set. We can only
access all the elements together. But we can also get a list of individual elements by
looping through the set.
Example:
Num=set([10,20,30,40,50])
for n in Num:
print(n)
Output:
10
20
30
40
50
c) Updating items in a set: We can add elements to a set by using add() method. There is
no specific index attached to the newly added element.
Example:
Num=set([10,20,30,40,50])
Num.add(60)
print(Num)
Output:
{10,20,30,40,50,60}
d) Removing items in set:
We can remove elements from a set by using discard() method. There is no specific
index attached to the newly added element.
Example:
Num=set([10,20,30,40,50])
Num.discard(50)
Print(Num)
Output:
{10,20,30,40}
Ans 2:-
a. add():-- It will add element to the set.
b. update():-- It will add elements from list/tuple/set to the sets.
c. pop():-- Removes and return an arbitrary set element.
d. remove(element):-- Remove an element from a set.
XI. Exercise
Note: Faculty must ensure that every group of students use different input value.
(Use blank space for answers or attach more pages if needed)
1. Write a Python program to create a set, add member(s) in a set and remove one
item from set.
2. Write a Python program to perform following operations on set: intersection of
sets, union of sets, set difference, symmetric difference, clear a set.
3. Write a Python program to find maximum and the minimum value in a set.
4. Write a Python program to find the length of a set.
s1={1,2,3,4,5}
print("SET1==",s1)
s1.add(8)
print("Add==",s1)
s1.remove(5)
print("Remove==",s1)
OUTPUT:--
SET1== {1, 2, 3, 4, 5}
Add== {1, 2, 3, 4, 5, 8}
Remove== {1, 2, 3, 4, 8}
Ans 2:-
s1={1,2,3,4,5}
s2={4,5,6,7,8}
print("SET1==",s1)
print("SET2==",s2)
print("Intersaction==",set.intersection(s1,s2))
print("Union==",set.union(s1,s2))
print("Diff==",set.difference(s1,s2))
print("symm diff==",set.symmetric_difference(s1,s2))
s1.clear()
print("s1==",s1)
OUTPUT:--
SET1== {1, 2, 3, 4, 5}
SET2== {4, 5, 6, 7, 8}
Intersaction== {4, 5}
Union== {1, 2, 3, 4, 5, 6, 7, 8}
Maharashtra State Board of Technical Education 58
Programming with Python (22616)
Diff== {1, 2, 3}
symm diff== {1, 2, 3, 6, 7, 8}
s1== set()
Ans 3:--
s1={1,2,3,4,5}
print("SET1==",s1)
print("MAX==",max(s1))
print("MIN==",min(s1))
OUTPUT:--
SET1== {1, 2, 3, 4, 5}
MAX== 5
MIN== 1
Ans 4:--
s1={1,2,3,4,5}
print("SET1==",s1)
print("LENGTH==",len(s1))
OUTPUT:--
SET1== {1, 2, 3, 4, 5}
LENGTH== 5
V. Practical Outcome(PrOs)
Write Python program to perform following operations on Dictionaries:
1. Create Dictionary
2. Access Dictionary elements
3. Update Dictionary
4. Delete Dictionary
5. Looping through Dictionary
Looping through Dictionary: A dictionary can be iterated using the for loop. If you
want to get both keys and the values in the output. You just have to add the keys and
values as the argument of the print statement in comma separation. After each iteration
of the for loop, you will get both the keys its relevant values in the output.
Example
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
for key, value in dict.items():
print(key, ' - ', value)
The above example contains both the keys and the values in the output. The text
‘Related to’ in the output showing the given key is related to the given value in the
output.
Name - Zara
Age - 7
Class - First
MSBTE
SEM
Type error:descriptor ‘items’ of ‘dict’ objects need an argument.
Ans 2:--
Google 1
Facebook 2
Microsoft 2
GFG 1
Youtube 3
Ans 3:--
{‘key1’:44,’key2’:566}[1,2,3,4]
XI. Exercise
Note: Faculty must ensure that every group of students use different input value.
(Use blank space for answers or attach more pages if needed)
1. Write a Python script to sort (ascending and descending) a dictionary by value.
2. Write a Python script to concatenate following dictionaries to create a new one.
a. Sample Dictionary:
b. dic1 = {1:10, 2:20}
c. dic2 = {3:30, 4:40}
d. dic3 = {5:50,6:60}
3. Write a Python program to combine two dictionary adding values for common
keys.
a. d1 = {'a': 100, 'b': 200, 'c':300}
b. d2 = {'a': 300, 'b': 200, 'd':400}
4. Write a Python program to print all unique values in a dictionary.
a. Sample Data: [{"V":"S001"}, {"V": "S002"}, {"VI": "S001"}, {"VI": "S005"},
{"VII":"S005"}, {"V":"S009"}, {"VIII":"S007"}]
5. Write a Python program to find the highest 3 values in a dictionary.
Ans 1:-
d={1:'one',5:'five',2:'two'}
print(d)
print(sorted(d))
OUTPT:--
Ans 2:--
dict1={1:10,2:20}
dict2={3:30,4:40}
dict3={5:50,6:60}
dict4={0:0}
dict4.update(dict1)
dict4.update(dict2)
dict4.update(dict3)
print("DICT==",dict4)
OUTPUT:--
Ans 3:--
dict1={'a':100,'b':200,'c':300}
dict2={'a':300,'b':200,'d':400}
dict3={}
print("dict1==",dict1)
print("dict2==",dict2)
dict3.update(dict1)
dict3.update(dict2)
OUTPUT:--
Ans 4:--
L=[{"V":"S001"},{"V":"S002"},{"VI":"S001"},{"VI":"S005"},{"VII":"5005"},{"V":"S009"},
{"VIII":"S007"}]
print("Original list==",L)
OUTPUT:--
Original list== [{'V': 'S001'}, {'V': 'S002'}, {'VI': 'S001'}, {'VI': 'S005'}, {'VII': '5005'}, {'V':
'S009'}, {'VIII': 'S007'}]
Unique values== {'S009', 'S002', 'S001', '5005', 'S005', 'S007'}
Ans 5:--
largestno=nlargest(3,dict,key=dict.get)
print("Largest values==",largestno)
OUTPUT:--
V. Practical Outcome(PrOs)
• Write Python program to demonstrate math built- in functions (Any 2 programs)
• Write Python program to demonstrate string built – in functions (Any 2 programs)
Function Description
ceil(x) Return the Ceiling value. It is the smallest integer, greater or equal
to the number x.
copysign(x, y) Returns x with the sign of y
cos(x) Return the cosine of x in radians
exp(x) Returns e**x
factorial(x) Returns the factorial of x
floor(x) Returns the largest integer less than or equal to x
fmod(x, y) Returns the remainder when x is divided by y
gcd(x, y) Returns the Greatest Common Divisor of x and y
log(x[, base]) Returns the Log of x, where base is given. The default base is e
log2(x) Returns the Log of x, where base is 2
log10(x) Returns the Log of x, where base is 10
pow(x, y) Return the x to the power y value.
remainder(x, y) Find remainder after dividing x by y.
radians(x) Convert angle x from degrees to radian
sqrt(x) Finds the square root of x
sin(x) Return the sine of x in radians
tan(x) Return the tangent of x in radians
Strip() Remove spaces at the beginning and at the end of the string:
startswith() Returns true if the string starts with the specified value
title() Converts the first character of each word to upper case
translate() Returns a translated string
upper() Converts a string into upper case
Ans 2:--
a. title() function is used to convert the first character of each word to uppercase and remaining
letters into lowercase.
str.title()
b. capitalize() method is similar to the title() but capitalize convert only first character to
uppercase and remaining to lowercase.
Str.capitalize()
Ans 3:--
1. title() function is used to convert the first character of each word to uppercase and remaining
letters into lowercase.
str.title()
2. strip() function is used to remove white spaces of the beginning or end of the string
str.strip()
XI. Exercise
Note: Faculty must ensure that every group of students use different input value.
(Use blank space for answers or attach more pages if needed)
1. Write a Python function that accepts a string and calculate the number of upper case
letters and lower case letters.
2. Write a Python program to generate a random float where the value is between 5
and 50 using Python math module.
s=input("Enter string:==")
print(s)
up=0
lo=0
for i in s:
if(i.islower()):
lo=lo+1
else:
up=up+1
print("Lower case=",lo)
print("Upper case=",up)
OUTPUT:--
Ans 2:--
import random
print(random.uniform(5,50))
OUTPUT:--
40.40171658064277
Practical No. 11: Develop user defined Python function for given problem:
• Function with minimum 2 arguments
• Function returning values
I. Practical Significance
All object oriented programming languages supports reusability. One way to achieve
this is to create a function. Like any other programming languages Python supports
creation of functions and which can be called within program or outside program.
Reusability and Modularity to the Python program can be provided by a function by
calling it multiple times. This practical will make learner use of modularized
programming using functions.
V. Practical Outcome(PrOs)
Develop user defined Python function for given problem:
1. Function with minimum 2 arguments
2. Function returning values
Ans 1:-
Hello
Hello
Hello
Hello
Ans 2:-
3
1
XI. Exercise
Note: Faculty must ensure that every group of students use different input value.
(Use blank space for answers or attach more pages if needed)
1. Write a Python function that takes a number as a parameter and check the number is
prime or not.
2. Write a Python function to calculate the factorial of a number (a non-negative
integer). The function accepts the number as an argument.
3. Write a Python function that accepts a string and calculate the number of upper case
letters and lower case letters.
Ans 1:--
def func(n):
for i in range(2,n+1):
if n%i==0:
break
if i==n:
print(n," is a prime number")
else:
print(n," is not a prime number")
n=int(input("Enter number"))
func(n)
OUTPUT:--
Enter number12
12 is not a prime number
Ans 2:--
def factorial(n):
if n==0:
return 1
else:
return n*factorial(n-1)
n=int(input("Enter number=="))
print(factorial(n))
OUTPUT:--
Enter number==5
120
Ans 3:--
def test(s):
up=0
lo=0
for i in s:
if(i.islower()):
lo=lo+1
else:
up=up+1
print("Lower case=",lo)
print("Upper case=",up)
s=input("Enter string==")
test(s)
OUPUT:--
Enter string==Hello
Lower case= 4
Upper case= 1
I. Practical Significance
While developing a computer application, more often than not the line of code (LOC)
can go beyond developer’s control. Such codes are tightly coupled and hence are
difficult to manage. Also one cannot reuse such code in other similar application.
Python supports modularized coding which allow developers to write a code in smaller
blocks. A module can define functions, classes and variables. A module can also
include runnable code. By using module students will be able to group related code
that will make the code easier for them to understand and use.
V. Practical Outcome(PrOs)
Write a program in Python to demonstrate use of:
1. Built-in module (e.g. keyword, math, number, operator)
2. User defined module
Ans 2:--
4
0.46780660299695465
6734577205207598
4
Ans 3:--
1581845027.4960284
1970-01-06
XI. Exercise
Note: Faculty must ensure that every group of students use different input value.
(Use blank space for answers or attach more pages if needed)
1. Write a Python program to create a user defined module that will ask your college
name and will display the name of the college.
2. Write a Python program that will calculate area and circumference of circle using
inbuilt Math Module
3. Write a Python program that will display Calendar of given month using Calendar
Module
Ans 1:-
//module
def college(name):
return name
import collegemod as c
a=input("Enter college name==")
print("College==",c.college(a))
OUTPUT:--
Ans 2:-
import math
radius=float(input("Enter radius of circle=="))
area=math.pi*radius**2
circum=2*math.pi*radius
print("Area==",area)
print("Circum==",circum)
OUTPUT:--
Ans 3:-
import calendar
month=int(input("Enter month=="))
year=int(input("Enter year=="))
print(calendar.month(year,month))
OUTPUT:--
Enter month==6
Enter year==1985
June 1985
Mo Tu We Th Fr Sa Su
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
Maharashtra State Board of Technical Education 85
Programming with Python (22616)
I. Practical Significance
Though Python is simple to learn language but it also very strong with its features. As
mentioned earlier Python supports various built in packages. Apart from built-in
package user can also make their own packages i.e. User Defined Packages. Numpy is
a general-purpose array-processing package. It provides a high-performance
multidimensional array object, and tools for working with these arrays. This practical
will allow students to write a code.
V. Practical Outcome(PrOs)
Write Python program to demonstrate use of:
• Built-in packages (e.g. NumPy, Pandas)
• User defined packages
print("Models of Mahendra")
for model in self.models:
print('\t%s ' % model)
3. Finally we create an __init .py file inside the directory, to let Python know that the
directory is a package.
Filename= init .py
from Maruti import Maruti
from Mahindra import Mahindra
4. To access package car, create sample.py file and access classes from directory car
Filename=sample.py
from Maruti import Maruti
from Mahindra import Mahindra
ModelMaruti=Maruti()
ModelMaruti.PModel()
ModelMahindra=Mahindra()
ModelMahindra.PModel()
Output:
Models of Maruti
800
Alto
WagonR
Models of Mahendra
Scorpio
Bolero
Xylo
Ans 2:--
Numpy is a python extension module to support efficient operation on arrays of homogeneous
data. It allows python to serve as a high-level language for manipulating numerical data, much
like IDL, Matlab, Octave or Yorick
XI. Exercise
Note: Faculty must ensure that every group of students use different input value.
(Use blank space for answers or attach more pages if needed)
1. Write a Python program to create two matrices and perform addition, subtraction,
multiplication and division operation on matrix.
2. Write a Python program to concatenate two strings.
3. Write a NumPy program to generate six random integers between 10 and 30.
print("Addition")
for i in range(len(matrix1)):
for j in range(len(matrix1[0])):
rmatrix[i][j] = matrix1[i][j] + matrix2[i][j]
for r in rmatrix:
print(r)
print("Subtraction")
for i in range(len(matrix1)):
for j in range(len(matrix1[0])):
rmatrix[i][j] = matrix1[i][j] - matrix2[i][j]
for r in rmatrix:
print(r)
print("Multiplication")
for i in range(len(matrix1)):
for j in range(len(matrix1[0])):
rmatrix[i][j] = matrix1[i][j] * matrix2[i][j]
for r in rmatrix:
print(r)
print("Division")
for i in range(len(matrix1)):
for j in range(len(matrix1[0])):
rmatrix[i][j] = matrix1[i][j] / matrix2[i][j]
for r in rmatrix:
print(r)
OUTPUT:--
Addition
[11, 13, 15]
[17, 19, 21]
[23, 25, 27]
Maharashtra State Board of Technical Education 91
Programming with Python (22616)
Subtraction
[9, 9, 9]
[9, 9, 9]
[9, 9, 9]
Multiplication
[10, 22, 36]
[52, 70, 90]
[112, 136, 162]
Division
[10.0, 5.5, 4.0]
[3.25, 2.8, 2.5]
[2.2857142857142856, 2.125, 2.0]
Ans 2:--
print("Concat==",str1+str2)
OUTPUT:--
Enter first string==hello
Enter second string==welcom
Concat== hellowelcom
Ans 3:--
import numpy as np
n=np.random.randint(low=10,high=30,size=6)
print(n)
OUTPUT:--
[20 18 16 16 11 19]
I. Practical Significance
While developing a large program with advance features of object oriented
programming one need to make use of more than one function having same name but
they perform different task altogether. This will improve in readability of program but
at time creates confusion in invoking desired function. Fortunately, Python supports
overloading and overriding of a function which allows developers to have different
functions with same name having same or different arguments. This practical will let
learner to develop programs using method overloading and overriding concept of
python.
V. Practical Outcome(PrOs)
Write a program in Python to demonstrate following operations:
1. Method overloading
2. Method overriding
class Student:
def hello(self, name=None):
if name is not None:
print('Hey ' + name)
else:
print('Hey ')
# Creating a class instance
std = Student()
# Call the method
std.hello()
# Call the method and pass a parameter
std.hello('Prasad')
Output
Hey
Hey Prasad
Method Overriding
The method overriding in Python means creating two methods with the same name but
differ in the programming logic. The concept of Method overriding allows us to
change or override the Parent Class function in the Child Class.
Example
# Python Method Overriding
class Employee:
def message(self):
print('This message is from Employee Class')
class Department(Employee):
def message(self):
print('This Department class is inherited from Employee')
emp = Employee()
emp.message()
print(' ')
dept = Department()
dept.message()
Output
This message is from Employee Class
Ans 2:--
I eat only plants. I am vegetarian. I breath oxygen
XI. Exercise
Note: Faculty must ensure that every group of students use different input value.
(Use blank space for answers or attach more pages if needed)
1. Write a Python program to create a class to print an integer and a character with
two methods having the same name but different sequence of the integer and the
character parameters. For example, if the parameters of the first method are of the
form (int n, char c), then that of the second method will be of the form (char c, int
n)
2. Write a Python program to create a class to print the area of a square and a
rectangle. The class has two methods with the same name but different number of
parameters. The method for printing area of rectangle has two parameters which
are length and breadth respectively while the other method for printing area of
square has one parameter which is side of square.
3. Write a Python program to create a class 'Degree' having a method 'getDegree' that
prints "I got a degree". It has two subclasses namely 'Undergraduate' and
'Postgraduate' each having a method with the same name that prints "I am an
Undergraduate" and "I am a Postgraduate" respectively. Call the method by
creating an object of each of the three classes.
Ans 1:--
class test:
def testci(self,c,i):
self.c=c
self.i=i
print("character==",self.c)
print("Integer==",self.i)
def testci(self,i,c):
self.c=c
self.i=i
print("character==",self.c)
print("Integer==",self.i)
a=test()
a.testci('a',12)
OUTPUT:--
character== 12
Integer== a
Ans 2:--
class area:
def find_area(self,side):
self.a=side*side
return self.a
def find_area(self,l,b):
self.a=l*b
return self.a
a=area()
result=a.find_area(4,6)
print(result)
OUTPUT:--
24
Ans 3:-
class degree:
def getdegree(self):
print("I got a degree")
class undergraduate(degree):
def getdegree(self):
Maharashtra State Board of Technical Education 98
Programming with Python (22616)
print("I am undergraduate")
class postgraduate(degree):
def getdegree(self):
print("I am postgraduate")
a=degree()
b=undergraduate()
c=postgraduate()
a.getdegree()
b.getdegree()
c.getdegree()
OUTPUT:--
I got a degree
I am undergraduate
I am postgraduate
I. Practical Significance
Inheritance allows us to define a class that inherits all the methods and properties from
another class. The existing class is called as Parent class or base class and the new
class which inherited from base class is called Child class or derived class.
V. Practical Outcome(PrOs)
Write a program in Python to demonstrate following operations:
• Simple inheritance
• Multiple inheritance
• The new class is called derived class or child class & 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 BaseClass1
#Body of base class
class DerivedClass(BaseClass1):
#body of derived - class
Example:
# Parent class created
class Parent:
parentname = ""
childname = ""
def show_parent(self):
print(self.parentname)
# Child class created inherits Parent class
class Child(Parent):
def show_child(self):
print(self.childname)
ch1 = Child() # Object of Child class
ch1.parentname = "Vijay" # Access Parent class attributes
ch1.childname = "Parth"
ch1.show_parent() # Access Parent class method
ch1.show_child() # Access Child class method
b) Multiple inheritance
• Python provides us the flexibility to inherit multiple base classes in the child class.
• Multiple Inheritance means that you're inheriting the property of multiple classes
into one. In case you have two classes, say A and B, and you want to create a new
class which inherits the properties of both A and B.
• So it just like a child inherits characteristics from both mother and father, in
Python, we can inherit multiple classes in a single child class.
Syntax:
Syntax:
class A:
# variable of class A
# functions of class A
class B:
# variable of class A
# functions of class A
class C(A, B):
# class C inheriting property of both class A and B
# add more properties to class C
Example:
class Add:
def Addition(self,a,b):
return a+b;
class Mul:
def Multiplication(self,a,b):
return a*b;
class Derived(Add,Mul):
def Divide(self,a,b):
return a/b;
d = Derived()
print(d.Addition(10,20))
print(d.Multiplication(10,20))
print(d.Divide(10,20))
Output:
30
200
0.5
Ans 2:--
1. Single inheritance
2. Multiple inheritance
3. Multilevel inheritance
4. Hierarchical inheritance
XI. Exercise
Note: Faculty must ensure that every group of students use different input value.
(Use blank space for answers or attach more pages if needed)
1. Create a class Employee with data members: name, department and salary. Create
suitable methods for reading and printing employee information
2. Python program to read and print students information using two classes using
simple inheritance.
3. Write a Python program to implement multiple inheritance
class Employee:
def get(self):
self.name=input("Enter name==")
self.dept=input("Enter department==")
self.salary=int(input("Enter salary=="))
def put(self):
print("NAME==",self.name)
print("DEPT==",self.dept)
print("SALARY==",self.salary)
ob=Employee()
ob.get()
ob.put()
OUTPUT:--
Enter name==abc
Enter department==co
Enter salary==12000
NAME== abc
DEPT== co
SALARY== 12000
Ans 2:--
class student:
def get(self):
self.name=input("Enter name==")
self.dept=input("Enter department==")
class display(student):
def put(self):
print("NAME==",self.name)
print("DEPT==",self.dept)
ob=display()
ob.get()
ob.put()
OUTPUT:--
Enter name==xyz
Enter department==co
NAME== xyz
DEPT== co
Ans 3:--
class Class1:
def m(self):
print("In Class1")
class Class2(Class1):
def m(self):
print("In Class2")
class Class3(Class1):
def m(self):
print("In Class3")
obj = Class4()
obj.m()
OUTPUT:--
In Class2
V. Practical Outcome(PrOs)
Write a program in Python to handle user defined exception for given problem
Ans 1:--
When we execute a python program , there may be few uncertain conditions occurs known as
error. Error also referred as bugs that are incorrect or inaccurate that may cause the problem in the
running of the program or may interrupt the execution of program. Errors occur at runtime are
known as exception
Ans 2:-
XI. Exercise
Note: Faculty must ensure that every group of students use different input value.
(Use blank space for answers or attach more pages if needed)
1. Write a Python program to Check for ZeroDivisionError Exception.
2. Write a Python program to create user defined exception that will check whether
the password is correct or not?
a=10
b=0
try:
d=a/b
print(d)
except ZeroDivisionError as obj:
print(obj)
except NameError as obj1:
print(obj1)
OUTPUT:--
division by zero
Ans 2:--
class pwdchk(Exception):
pass
def checkpwd():
pwd="abcd"
upwd=input("Enter password==")
try:
if(pwd!=upwd):
raise pwdchk("WRONG")
print("CORRECT")
except pwdchk as obj:
print(obj)
checkpwd()
OUTPUT:--
Enter password==sgdh
WRONG