Programming With Python Lab Manual
Programming With Python Lab Manual
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
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.
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
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.
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!
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)
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
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
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
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)
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
XI. References / Suggestions for further Reading
1. https://www.w3schools.com/Python/Python_operators.asp
2. https://www.geeksforgeeks.org/basic-operators-Python/
3. https://www.guru99.com/Python-operators-complete-tutorial.html
4. https://www.tutorialspoint.com/Python/Python_basic_operators
5. https://www.youtube.com/watch?v=v5MR5JnKcZI
6. https://www.youtube.com/watch?v=fN8yDMdl_aw
V. Practical Outcomes(PrOs)
Develop Python program using Conditional operators: if, if-else and Nested if
statement.
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.
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
V. Practical Outcomes(PrOs)
Write Python program to demonstrate use of looping statements:
‘while’ loop
‘for’ loop
Nested loops
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
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)
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
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.
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;
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
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
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
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}
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.
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
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
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.
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
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
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
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.
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
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
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.
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
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
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
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
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.
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
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
------------
This Department class is inherited from Employee
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.
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
XII. References / Suggestions for further Reading
1. https://stackabuse.com/overloading-functions-and-operators-in-Python/
2. https://www.tutorialgateway.org/method-overriding-in-Python/
3. https://www.youtube.com/watch?v=HIkoX4pVmrI
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
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
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
V. Practical Outcome(PrOs)
Write a program in Python to handle user defined exception for given problem
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
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?
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................