CM5101 Python LabManual
CM5101 Python LabManual
A Laboratory Manual
For
(CM5101)
Semester –VI
(CM/IT)
PO1 Basic and Discipline specific knowledge: Apply knowledge of basic mathematics, science
and engineering fundamentals and engineering specialization to solve the IT related
engineering problems.
PO2 Problem analysis: Identify and analyse well-defined IT related engineering problems using
codified standard methods.
PO3 Design/ development of solutions: Design IT solutions for well-defined technical problems
and assist with the design of systems components or processes to meet specified needs.
PO4 Engineering Tools, Experimentation and Testing: Apply modern engineering tools and
appropriate technique to conduct standard tests and measurements to IT related processes.
PO5 Engineering practices for society, sustainability and environment: Apply IT (automation)
solutions in context of society, sustainability, environment and ethical practices.
PO7 Life-long learning: Recognize and analyse individual need for, and have the preparation and
ability to engage in independent and life-long learning in the context of technological changes
in IT industry.
PSO 1.Hardware and Networking: Maintain, troubleshoot & provide hardware and networking
support. Set up hardware and networking unit by applying IT related standards and principles.
PSO 3. Software Development: Develop, test and maintain software using IT technologies and
tools.
Content Page
List of Practical’s and Progressive Assessment Sheet
Total Marks
Department Of Computer Engg.and Information Technology G.P.Pune viii
Programming with Python (CM5101)
Practical No. 1:
Title: Install and configure Python IDE
I. Practical Significance
Python is a high-level, general-purpose, interpreted, interactive, object-oriented
dynamic programming language. Student will able to select and install appropriate
installer for Python in windows and package manager for Linux in order to setup
Python environment for running programs.
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.
XII. 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.
Practical No. 2:
Title: Write simple Python program to display message on screen
I. Practical Significance
Python is a high level language which is trending in recent past. To make it more user
friendly developers of Python made sure that it can have two modes Viz. Interactive
mode and Script Mode. The Script mode is also known as normal mode and uses
scripted and finished .py files which are run on interpreter whereas interactive mode
supports command line shells. Students will able to understand how to run programs
using Interactive and Script mode.
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!
Note: Below given are few sample questions for reference. Teachers must design
more such questions to ensure the achievement of identified CO.
1. List different modes of Programming in Python
2. Describe procedure to execute program using Interactive Mode
3. State the steps involved in executing the program using Script Mode
4. State the procedure to make file executable
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 “Government Polytechnic –IT” using Script Mode
(Space for answers)
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
Practical No. 3:
Title: Write simple Python program using operators: Arithmetic
Operators, Logical Operators, Bitwise Operators
I. Practical Significance
Operators are used to perform operations on values and variables. Operators can
manipulate individual items and returns a result. The data items are referred as
operands or arguments. Operators are either represented by keywords or special
characters. Here are the types of operators supported by Python:
Arithmetic Operators
Assignment Operators
Relational or Comparison Operators
Logical Operators
Bitwise Operators
Identity Operators
Membership Operators
Students will be able to use various operators to check the condition and get
appropriate result by performing different operation with the help of supported
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
Government Polytechnic Pune 16
Programming with Python (CM5101)
Membership Operators
Membership operators are used to test if a sequence is presented in an object:
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)
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
Practical No. 4
Title: Write simple Python program to demonstrate use of
conditional statements: if’ statement, ‘if … else’ statement,
Nested ‘if’ statement.
I. Practical Significance
Decision making is anticipation of conditions occurring while execution of the
program and specifying actions taken according to the conditions. Decision structures
evaluate multiple expressions which produce TRUE or FALSE as outcome. You need
to determine which action to take and which statements to execute if outcome is
TRUE or FALSE otherwise
V. Practical Outcomes(PrOs)
Develop Python program using Conditional operators: if, if-else and Nested if
statement.
If condition:
Statement(s)
Example:
i=10
if(i > 20):
print ("10 is less than 20")
print ("We are Not in if ")
Output: We are Not in if
b) If-else Statement: The if statement alone tells us that if a condition is true it will
execute a block of statements and if the condition is false it won’t. But what if we
want to do something else if the condition is false. Here comes the else statement. We
can use the else statement with if statement to execute a block of code when the
condition is false.
Syntax:
if (condition):
# if Condition is true, Executes this block
else:
# if condition is false, Executes this block
Example:
i=10;
if(i<20):
print ("i is smaller than 20")
else:
print ("i is greater than 25")
Output:
i is smaller than 20
c) Nested-if Statement:
A nested if is an if statement that is the target of another if statement. Nested if
statements means an if statement inside another if statement. Yes, Python allows us to
nest if statements within if statements. i.e, we can place an if statement inside another
if statement.
Syntax:
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here
Example:
i =10
if(i ==10):
# First if statement
if(i < 20):
print ("i is smaller than 20")
# Nested - if statement will only be executed if statement above is true
if (i < 15):
print ("i is smaller than 15 too")
else:
print ("i is greater than 15")
Output:
i is smaller than 20
i is smaller than 15 too
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.
Practical No. 5
Title: Write Python program to demonstrate use of looping
statements: ‘while’ loop, ‘for’ loop and Nested loop
I. Practical Significance
While developing a computer application one need to identify all possible situation.
One situation is to repeat execution of certain code block/ line of code. Such situation
can be taken care by looping system. Like all other high level programming language,
Python also supports all loop structure. To keep a computer doing useful work we
need repetition, looping back over the same block of code again and again. This
practical will describe the different kinds of loops in Python.
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)
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
Practical No. 6
Title: Write Python program to demonstrate use of looping statements:
continue, pass, break.
I. Practical Significance
V. Practical Outcome(PrOs)
Develop Python program to perform following operations on Loop:
continue,pass,break.
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.
Practical No: 7
1. 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.
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]
7. Resources required
Sr. Name of Specification Quantity Remarks
No. Resource (If any)
8. Program (Coding)
............................................................................................................................................................
......................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
9. Result (Output)
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
10. Conclusions
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
Government Polytechnic Pune 44
Programming with Python (CM5101)
.........................................................................................................................................................
12. 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.
14. Rubrics for evaluation (subject to modification as per the suggestions from the
HODs/Faculties)
Practical No. 8
1. 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.
5. Practical Outcome(PrOs)
Write Python program to perform following operations on Tuples:
1. Create Tuple
2. Access Tuple
3. Update Tuple
4. Delete Tuple
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;
7. Resources required
Sr. Name of Specification Quantity Remarks
No. Resource (If any)
. 9. Program (Coding)
........................................................................................................................................................
........................................................................................................................................................
........................................................................................................................................................
........................................................................................................................................................
........................................................................................................................................................
........................................................................................................................................................
........................................................................................................................................................
........................................................................................................................................................
........................................................................................................................................................
........................................................................................................................................................
........................................................................................................................................................
........................................................................................................................................................
........................................................................................................................................................
Government Polytechnic Pune 49
Programming with Python (CM5101)
........................................................................................................................................................
........................................................................................................................................................
........................................................................................................................................................
........................................................................................................................................................
................
10.Result (Output)
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
............................................................................................................................................................
......................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
........................................................................................................................................................
11.Conclusion
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
.........................................................................................................................................................
12. 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
........................................................................................................................................................
........................................................................................................................................................
........................................................................................................................................................
........................................................................................................................................................
........................................................................................................................................................
........................................................................................................................................................
........................................................................................................................................................
........................................................................................................................................................
........................................................................................................................................................
........................................................................................................................................................
........................................................................................................................................................
..............
14. Rubrics for evaluation (subject to modification as per the suggestions from the
HODs/Faculties)
Practical No. 9
Set: Create Set, Access Set elements, Update Set, Delete Set
1. Practical Significance
A set is an unordered collection of items. Every element is unique (no duplicates) and
must be immutable (which cannot be changed). A set is created by placing all the
items (elements) inside curly braces {}, separated by comma or by using the built-in
function set(). It can have any number of items and they may be of different types
(integer, float, tuple, string etc.). This practical will make students to work on Set data
structure supported in Python.
5. Practical Outcome(PrOs)
Develop Python program to perform following operations on Sets: Create, Access,
Update and Delete set
10.Result(Output)
........................................................................................................................................................
Government Polytechnic Pune 54
Programming with Python (CM5101)
........................................................................................................................................................
........................................................................................................................................................
........................................................................................................................................................
...
11. Conclusion
........................................................................................................................................................
........................................................................................................................................................
........................................................................................................................................................
........................................................................................................................................................
...
12. 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.
14. Rubrics for evaluation (subject to modification as per the suggestions from the
HODs/Faculties)
Practical No. 10
5. 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
Government Polytechnic Pune 58
Programming with Python (CM5101)
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"},
.........................................................................................................................................................
.........................................................................................................................................................
......................................................................................................................................................... .
........................................................................................................................................................ .
........................................................................................................................................................ ..
....................................................................................................................................................... ..
....................................................................................................................................................... ...
...................................................................................................................................................... ...
.................................................................................................................................................. ...
......................................................................................................................................................
9. Program (Coding)
........................................................................................................................................................
........................................................................................................................................................
........................................................................................................................................................
........................................................................................................................................................
........................................................................................................................................................
........................................................................................................................................................
........................................................................................................................................................
........................................................................................................................................................
........................................................................................................................................................
........................................................................................................................................................
.........
10.Result(Output)
........................................................................................................................................................
........................................................................................................................................................
........................................................................................................................................................
........................................................................................................................................................
...
11. Conclusion
........................................................................................................................................................
........................................................................................................................................................
........................................................................................................................................................
........................................................................................................................................................
...
14. Rubrics for evaluation (subject to modification as per the suggestions from the
HODs/Faculties)
Practical No. 11
Title: i.Write Python program to demonstrate math built-in functions
(Any 2 programs)
ii. Write Python program to demonstrate string built-in functions
(Any 2 programs)
1. Practical Significance
Like any other 3rd generation language, Python also supports in-built functions to
perform some traditional operations on String and Numbers. The math module is used
to access mathematical functions in the Python. All methods of these functions are
used for integer or real type objects, not for complex numbers. The math module is a
standard module in Python and is always available. To use mathematical functions
under this module, you have to import the module using import math. String functions
will let user to develop a code using basic and advance functions which works on
string. This practical will let learner to use mathematical and string related functions.
5. 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
log(x[, base]) Returns the Log of x, where base is given. The default base is e
Function Description
endswith() Returns true if the string ends with the specified value
find() Searches the string for a specified value and returns the position
of where it was found
index() Searches the string for a specified value and returns the position
of where it was found
Government Polytechnic Pune 64
Programming with Python (CM5101)
isalnum() Returns True if all characters in the string are alphanumeric
isalpha() Returns True if all characters in the string are in the alphabet
islower() Returns True if all characters in the string are lower case
isupper() Returns True if all characters in the string are upper case
rfind() Searches the string for a specified value and returns the last
position of where it was found
rindex() Searches the string for a specified value and returns the last
position of where it was found
split() Splits the string at the specified separator, and returns a list
Strip() Remove spaces at the beginning and at the end of the string:
startswith() Returns true if the string starts with the specified value
7. Resources required
Sr. Name of Specification Quantity Remarks
No. Resource (If any)
........................................................................................................................................................
........................................................................................................................................................
........................................................................................................................................................
........................................................................................................................................................
...
11. Conclusion
........................................................................................................................................................
........................................................................................................................................................
........................................................................................................................................................
........................................................................................................................................................
...
12. 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.
14. Rubrics for evaluation (subject to modification as per the suggestions from the
HODs/Faculties)
Practical No. 12
Title: Develop user defined Python function for given problem:
∙ Function with minimum 2 arguments
∙ Function returning values
1. 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.
5. Practical Outcome(PrOs)
Develop user defined Python function for given problem:
1. Function with minimum 2 arguments
2. Function returning values
a) Creating a function: In Python, we can use def keyword to define the function.
Syntax:
Government Polytechnic Pune 69
Programming with Python (CM5101)
def my_function():
function-suite
return <expression>
b) Calling a function: To call the function, use the function name followed by the
parentheses.
def hello_world():
print("hello world")
hello_world()
Output:
hello world
c) Arguments in function: The information into the functions can be passed as the
argumenta. The arguments are specified in the parentheses. We can give any number
of arguments, but we have to separate them with a comma.
Example
#defining the function
def func (name):
print("Hi ",name);
#calling the function
func("ABC")
Output:
hi ABC
7. Resources required
Sr. Name of Specification Quantity Remarks
No. Resource (If any)
........................................................................................................................................................
........................................................................................................................................................
........
10.Result(Output)
........................................................................................................................................................
........................................................................................................................................................
........................................................................................................................................................
........................................................................................................................................................
...
11. Conclusion
........................................................................................................................................................
........................................................................................................................................................
........................................................................................................................................................
........................................................................................................................................................
12. 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.
.
........................................................................................................................................................
........................................................................................................................................................
........................................................................................................................................................
..........
13. References / Suggestions for further Reading
1. https://www.tutorialspoint.com/Python/Python_functions.htm
2. https://www.javatpoint.com/Python-functions
3. https://www.youtube.com/watch?v=9Os0o3wzS_I
4. https://www.youtube.com/watch?v=NE97ylAnrz4
14. Rubrics for evaluation (subject to modification as per the suggestions from the
HODs/Faculties)
Practical no: 13
1. 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.
5. Practical Outcome
Write a program in Python to demonstrate use of:
1. Built-in module (e.g. keyword, math, number, operator)
2. User defined module
8. Resources Required
9. Precautions to be Followed
1. Handle computer system and peripherals with care.
2. Follow safety practices.
1)
2)
3)
14. Conclusions
……………………………………………………………………………………..
……………………………………………………………………………………..
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
17. Rubrics for evaluation(subject to modification as per the suggestions from the
HODs/Faculties)
1. Practical Significance:
Though Python language is simple to learn but it is 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
5. Practical Outcome
Write a program in Python to demonstrate use of:
1. Built-in packages (e.g., NumPy, Pandas)
2. User defined packages
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()
Government Polytechnic Pune 80
Programming with Python (CM5101)
ModelMahindra.PModel()
Output:
Models of Maruti
800
Alto
WagonR
Models of Mahendra
Scorpio
Bolero
Xylo
7. Practical setup/figures circuits (if needed)
NA
8. Resources Required
9. Precautions to be Followed
3. Handle computer system and peripherals with care.
4. Follow safety practices.
1)
2)
3)
14. Conclusions
……………………………………………………………………………………..
……………………………………………………………………………………..
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.
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
Government Polytechnic Pune 82
Programming with Python (CM5101)
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
17. Rubrics for evaluation(subject to modification as per the suggestions from the
HODs/Faculties)
1. 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 a 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.
5. Practical Outcome
Write Python Program 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:
Government Polytechnic Pune 84
Programming with Python (CM5101)
print('Hey ')
# Creating a class instance
std = Student()
# Call the method
std.hello()
# Call the method and pass a parameter
std.hello('Akshay')
Output
Hey
Hey Akshay
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
7. Practical setup/figures circuits (if needed)
NA
8. Resources Required
9. Precautions to be Followed
1. Handle computer system and peripherals with care.
2. Follow safety practices.
1)
2)
3)
14. Conclusions
……………………………………………………………………………………..
……………………………………………………………………………………..
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.
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
17. Rubrics for evaluation(subject to modification as per the suggestions from the
HODs/Faculties)
Practical no: 16
1. 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.
5. Practical Outcome
Write Python Program to demonstrate following operations:
Simple Inheritance
Multiple Inheritance
a) Simple Inheritance:
The mechanism of designing or constructing classes from other classes is called 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 = "Akshay"
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:
Government Polytechnic Pune 90
Programming with Python (CM5101)
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
8. Resources Required
9. Precautions to be followed
3. Handle computer system and peripherals with care.
4. Follow safety practices.
1)
2)
3)
14. Conclusions
……………………………………………………………………………………..
……………………………………………………………………………………..
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
Government Polytechnic Pune 92
Programming with Python (CM5101)
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
17. Rubrics for evaluation(subject to modification as per the suggestions from the
HODs/Faculties)
1. Practical Significance:
Files are named locations on disk to store related information. They are used to permanently store
data in a non-volatile memory (e.g. hard disk). Since Random Access Memory (RAM) is volatile
(which loses its data when the computer is turned off), we use files for future use of the data by
permanently storing them.
When we want to read from or write to a file, we need to open it first. When we are done, it
needs to be closed so that the resources that are tied with the file are freed. File handling is an
important part of any web application. Python has several functions for creating, reading,
updating, and deleting files.
5. Practical Outcome
Write Python Program to demonstrate File Handling through:
Opening file in different modes
Accessing file
Reading and Writing file
Closing file
Renaming and Deleting file
Government Polytechnic Pune 94
Programming with Python (CM5101)
Closing file
When we are done with performing operations on the file, we need to properly close the file.
Closing a file will free up the resources that were tied with the file. It is done using
the close() method available in Python. Python has a garbage collector to clean up unreferenced
objects but we must not rely on it to close the file.
Example:
# Open a file
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
8. Resources Required
9. Precautions to be followed
1. Handle computer system and peripherals with care.
2. Follow safety practices.
1)
2)
3)
14. Conclusions
……………………………………………………………………………………..
……………………………………………………………………………………..
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
Government Polytechnic Pune 98
......................................................................................................................................................
Programming with Python (CM5101)
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
17. Rubrics for evaluation(subject to modification as per the suggestions from the
HODs/Faculties)
Practical no: 18
Title: Write Python Program to handle user defined exception for given problem.
1. Practical Significance:
Exceptions are uncovered errors that can occur during run time of a program. Python facilitates
its developer to handle such exceptional cases which can then avoid abrupt termination of a
program. One can create user-defined or custom exceptions by creating a new exception class in
Python. Exceptions need to be derived from the Exception class, either directly or indirectly. This
practical will let students to write their own exceptions and avoid program from abrupt
termination.
5. Practical Outcome
Write a program in Python to handle user defined exception for given problem
Python has many built-in exceptions which forces your program to output an error
when something in it goes wrong. However, sometimes you may need to create
custom exceptions that serves your purpose.
A list of common exceptions:
ZeroDivisionError: Occurs when a number is divided by zero.
NameError: It occurs when a name is not found. It may be local or global.
IndentationError: If incorrect indentation is given.
IOError: It occurs when Input Output operation fails.
EOFError: It occurs when the end of the file is reached, and yet operations are
being performed.
In Python, users can define such exceptions by creating a new class. This exception
class has to be derived, either directly or indirectly, from Exception class. Most of the
built-in exceptions are also derived from this class.
Example:
def input_age(age):
Government Polytechnic Pune 100
Programming with Python (CM5101)
try:
assert int(age) > 18
except ValueError:
return 'ValueError: Insert integer value'
else:
return 'You are Adult'
output:
>>> print(input_age(25))
You are Adult
>>> print(input_age('abc'))
ValueError: Insert integer value
8. Resources Required
9. Precautions to be followed
1. Handle computer system and peripherals with care.
2. Follow safety practices.
Government Polytechnic Pune 101
Programming with Python (CM5101)
1)
2)
3)
14. Conclusions
……………………………………………………………………………………..
……………………………………………………………………………………..
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
......................................................................................................................................................
17. Rubrics for evaluation(subject to modification as per the suggestions from the
HODs/Faculties)