Python Lab Manual
Python Lab Manual
TECHNOLOGY
Programming with Python Laboratory Manual
[B22CI0305]
INDEX
Sl.No Name Page
Number
4. Program Outcome 5
8. List of Experiments 11
9. Viva Questions 40
School Vision
To produce excellent quality technologists and researchers of global standards in
computing and Information technology who have potential to contribute to the
development of the nation and the society with their expertise, skills, innovative problem-
solving abilities, strong moral and ethical values.
School Mission
To create state of the art computing labs infrastructure and research facilities in
information technology.
To provide student-centric learning environment in Computing and Information
technology through innovative pedagogy and education reforms.
To encourage research, innovation and entrepreneurship in computing and information
technology through industry/academia collaborations and extension activities
Organize programs through club activities for knowledge enhancement in thrust areas of
information technology.
To enhance leadership qualities among the youth and enrich personality traits, promote
patriotism, moral and ethical values.
Program Educational Objective
After few years of graduation, the graduates of B. Tech CS & SE will –
PEO-1: Pursue higher education in the core or allied areas of Computer Science and
Systems Engineering.
PEO-2: Have technical career in the core or allied areas of Computer Science Systems
Engineering or start entrepreneurial activity for the growth of the economy.
PEO-3: Continue to learn and to adapt to ever changing technologies in the core or allied
areas of Computer Science and Systems Engineering.
Program Outcomes (PO’s)
On successful completion of the program, the graduates of B. Tech CS & SE program will be
able to:
Course Details
COURSE OBJECTIVE (S):
The objectives of this course are to:
1. Explain the fundamentals of python programming language constructs and their
applications.
2. Inculcate knowledge of parsing of regular expressions and their usage in various application
domains.
3. Gain expertise in Object oriented programming and NumPy package.
4. Discuss the files, Pandas and Data Virtualization concepts.
Lab Requirements:
Following are the required hardware and software for this lab, which is available in the
laboratory.
Minimum System requirements:
Processors: Intel Atom® processor or Intel® Core™ i3 processor.
Disk space: 1 GB.
Operating systems: Windows* 7 or later, macOS, and Linux.
Python* versions: 2.7.X, 3.6.X.,3.8.X
Guidelines to Students:
Equipment in the lab for the use of student community. Students need to maintain a proper
decorum in the computer lab. Students must use the equipment with care. Any damage is
caused is punishable.
Students are required to carry their observation / programs book with completed exercises
while entering the lab.
Students are supposed to occupy the machines allotted to them and are not supposed to
talk or make noise in the lab. The allocation is put up on the lab notice board.
Lab can be used in free time / lunch hours by the students who need to use the systems
should take prior permission from the lab in-charge.
Lab records need to be submitted on or before date of submission.
Students are not supposed to use flash drives.
ACTIVITY MARKS
Record
TOTAL
PSO2
PSO3
PO10
PO11
PO12
CO#/P
PO1
PO2
PO3
PO4
PO5
PO6
PO7
PO8
PO9
Os
B22CI0305.1 3 1 1 2 1 1 1 3
B22CI0305.2 3 2 3 2 1 1 3
B22CI0305.3 3 1 2 1 2 1 1 3
B22CI0305.4 3 2 2 1 1 3 3 3
B22CI0305.5 1 2 2
B22CI0305.6 2 1 1 2 2
Note:1-Low,2-Medium,3-High
Sl No ACTIVITY MARKS
01 Conduction
02 Viva Voce
03 Modification
Total
Total
List of Experiments
PRACTICE:
Consider the text file “Emp.txt”, with the details of Employees like
EMP_CODE, EMP_NAME, BASIC_SALARY, DA, GROSS_SALARY,
NET_SALARY, LIC, PF and TOTAL-DEDUCTIONS. Read EMP_CODE,
EMP_NAME, BASIC_SALARY, DA, LIC and PF from the user using
input() and compute the following:
10. File Handling.
TOTAL_DEDUCTIONS= (LIC+PF)
GROSS_SALARY= BASIC_SALARY+ DA
NET_SALARY= GROSS_SALARY – TOTAL_DEDUCTIONS.
Write the above data to file for each employee. Read the content of
“Emp.txt” and display the details of each employee
A “CAR” has the attributes COMPANY_NAME, MODEL, COLOR,
MANUFACUTING_YEAR and PRICE. A Class is required to be created
for “CAR” to store the above attributes and perform the following
11. operations:
Get the details of “CAR” object from user and store into Array of
objects
Display the details ofSystem
Airline Reservation “CAR” object based
contains theon “COMPANY”,
attributes “MODEL”
of passengers Classes and
and “PRICE”.
such as NAME, PAN_NO. MOBILE_NO, EMAIL_ID, SOURCE, objects
DESTINATION, SEAT-NO, AIR-FARE and TRAVEL_DATE. A Class is usage.
required to be created for “Airlilne” with the above attributes and
12. perform the following operations:
Get the details of “Airline” object from user and store into Array of
objects
List details of all the passengers who travelled From “Bengaluru to
London”.
List details
“Arr_1” of integer
is an all the array
passengers
of sizewho
M x travelled From
N. Size and “Chicago
content to
of the
th
Beijing”
array onbe
is to 10readof Feb,
using2020.
input() by using the user defined function
READ_DATA(). It is required to display the NumPy arrays
13. Diagonal elements of”Arr_1”
usability.
Elements of mth row (row no should be entered by user)
Elements of nthcolumn (column no should be entered by user)
The dictionary “DICT1” contains the pass percentage of each
semester of B. Tech in CSE, where, “Semester” acts as the key and
Pandas Series
14. “Pass Percentage” acts as the value. A Python Pandas dataframe is
usability.
required to be created using the dictionary “DICT1” and display it
using a user defined function.
1. Develop a program to read the student details like Name, SRN, and Marks in
three subjects. Display the student details, total marks and percentage with
suitable messages.
Algorithm:
1. Start
2. Read Name, SRN, Marks of 3 subjects
3. Compute Total marks
4. Compute Percentage of the student
5. Display Student details
6. Stop
Code:
Name = input("Enter the name of the student : ")
print("Student Details\n=========================")
Output:
Algorithm:
1. Start
2. Read value of n
3. Use for loop
i. To Print ‘n’ numbers by using range function
ii. To Print numbers from -5 to +5
iii. To Print even numbers and odd numbers from 1 to n
4. Stop
Code:
i. Range function with one parameter
for i in range(n+1):
Output:
Output:
Output:
Output:
An Armstrong number is a number that is equal to the sum of the cubes (for 3 digit number)
of its own digits.
Algorithm –
1. Start
2. Read a number to check wether it is Armstrong number or not.
3. Number is divided into individual digits and find cubes of each digit
4. If summation of cubes of each digit is equal to given number then it is an Armstrong
number else it is not an Armstrong number.
5. Stop
Code -
num = int(input("Enter 3-digit number : "))
sum = 0
temp = num
digit = temp % 10
temp = temp//10
if sum==num:
else:
Output:
4. “List1” is a list that contains the “N” different SRN of students read using a
user defined function with the help of input(). SRN of “M” more students are
to be appended or inserted into “List1” at the appropriate place and also
return the index of the SRN entered by user.
Algorithm:
4. Increment i by 1 until n or m
Coding:
list1 = [ ]
def read( ):
n = int(input("Enter Size of list: "))
for i in range(0, n):
srn = int(input("Enter SRN"))
list1.append(srn)
print(list1)
read( )
f=input("You want to add some more SRNs..? Yes/No:")
if f = ="Yes":
pos=int(input("Enter the position:"))
s=int(input("Enter SRN:"))
list1.insert(pos,s)
else:
pass
print(list1)
p=int(input("enter the element from the list to be print its index "))
print("Index of ele",p,"=",list1.index(p))
Output
Enter number of SRNs you want to add : 3
Enter SRN:121
Enter SRN:122
Enter SRN:123
[121, 122, 123]
You want to add some more SRNs..? Yes/No: Yes
Enter the position:1
Enter SRN: 120
[121, 120, 122, 123]
Enter the element from the list to be print its index : 122
Index of ele 122=2
5. “Tuple1” and “Tuple2” are two tuples that contain “N” different data type
read using the user defined function “READ” with the help of input( ).
Elements of “Tuple1” and “Tuple2”are to be read one at a time and the
“larger” value among them should be put into “Tuple3”.
Algorithm:
Coding:
t1 = ( )
t2 = ( )
L1=list(t1)
L2=list(t2)
def read( ):
count = int(input("Enter the total count of elements :"))
print("enter elements tuple1")
for i in range(0,count):
L1.append(int(input()))
print("enter elemets tuple2")
for i in range(0,count):
L2.append(input())
read( )
t1=tuple(L1)
t2=tuple(L2)
print("tuple1:",t1)
print("tuple2:",t2)
tuple3 = (max(t1),max(t2))
print("Max of tuple1 & tuple2",t3)
Output
Enter the total count of elements: 4
Enetr elements tuple1: 10,20,40,60
Enter elements tuple1: ‘a’,’b’,’c’
Max of tuple1 & tuple2 (60, c)
6. Set1 and Set2 are the two sets that contain unique integers. Set3 is to be
created by taking the union or intersection of Set1 and Set2using the user
defined function Operation( ). Perform either union or intersection by reading
choice from user. Do not use built in functions union( ) and intersection( ) and
also the operators “|” and “&“.
Coding:
#Union Function
def uni( ):
for i in s2:
if i in s1:
pass
else:
s1.add(i)
print("Union of S1 and S2:",s1)
#Intersection Function
def inter( ):
s3=set( )
for i in s2:
if i in s1:
s3.add(i)
else:
pass
print("Intersection of S1 and S2:",s3)
s1=set( )
s2=set( )
n1=int(input("Enter length of set1"))
for i in range(n1):
s1.add(int(input()))
Output
Union:
Enter length of set1 3
1
2
3
Enter length of set2 3
2
3
2
S1: {1, 2, 3}
S2: {2, 3}
ENTER YOUR CHOICE: 1. UNION 2. INTERSECTION
1
Union of S1 and S2: {1, 2, 3}
Intersection:
Enter length of set1 3
1
2
3
Enter length of set2 3
2
3
2
S1: {1, 2, 3}
S2: {2, 3}
ENTER YOUR CHOICE: 1. UNION 2. INTERSECTION
2
Intersection of S1 and S2: {2, 3}
Invalid Choice:
Enter length of set1 2
1
2
Enter length of set2 2
2
3
S1: {1, 2}
S2: {2, 3}
ENTER YOUR CHOICE: 1. UNION 2. INTERSECTION
6
INVALID CHOICE
Algorithm:
1. Create the set names as people ,vampires and dracula : initialize the values to the
created sets
2. Create user defined function union() and perform its operation on any two sets ( i.e
people and vampires)
2.1 population = people.union (vampires)
3. Display population
4. Apply union operator: repeat step 2.1 and 3
5. Create two set which assigned to set1 and set 2
6. for i in range (5) and add into set1
7. for i in range (3,9) and add into set2
8. Create and Perform user defned function intersection () function on set 1 , set 2 and
result stored in set3
9. Dispay set3
10. Apply intersection operation and repeat step 8 & 9
7. The Dictionary “Dict1” contains N Elements and each element has the
operator as the key and operands as values. User reads two operands and an
operator and performs the operation on the elements of “Dict1” based on the
operator using a user defined function and displays the results.
Coding:
def sub( ):
a=dict1["-"]
print ("Subtraction of ",a,"is:")
print(a[i]-a[i+1])
def mul( ):
a=dict1["*"]
print ("Multiplication of ",a,"is:")
print(a[i]*a[i+1])
def div( ):
a=dict1["/"]
print ("Division of ",a,"is:")
print(a[i]/a[i+1])
x =input("enter an operator:")
if x=="+":
add( )
elif x=="-":
sub( )
elif x=="*":
mul( )
elif x=="/":
div( )
else:
print("Invalid operator")
Output
Algorithm:
Algorithm 1:
1. Read a String input
2. Get the substring using indexing sequence
a. String[start : end]
b. String[ : end]
c. String[start : -end]
3. Print the sub string.
Algorithm 2:
1. Read a String input
2. Get the substring using slice constructor
a. String[slice(stop_index)]
b. String[slice(start,stop,step)]
3. Print the sub string.
Coding:
def substr1( ):
substring=Str1[index1:index2]
substr1( )
Output
8. ii. A string containing multiple words is to be read from the user one at a
time after reading perform following operations.
a. Convert all the strings to uppercase and display
b. Split the words of a string using space as the separation character and
display.
Algorithm:
1. Read the input from the user
2. Use upper() function on the input.
3. Use split() function on the input
Coding:
Output
Tell me about yourself
i am ramu from bangalore
You Told: I AM RAMU FROM BANGALORE
Output
Tell me about yourself
9. Consider the text file, “Std.txt”, with the details of students like SRN,
Name, semester, and section and Avg_Marks. Read the file, “Std” and
display the details of all the students of 4 th Semester “ A” Section who
have scored more than 75%.
Algorithm:
Coding:
Output:
10. Consider the text file “Emp.txt”, with the details of Employees like
Emp_code, Emp_name, Basic_Salary, DA,Gross_salary, Net_salary,
LIC and PF, Total_deductions. Read Emp_code, Emp_name,
Basic_Salary, DA, LIC and PF from the user using input() and
compute the following:
i)Total_Deductions= (LIC+PF)
ii) Gross_Salary= Basic_Salary+ DA
iii) Net_Salary= Gross_Salary – Total_Deductions.
Write the above data to file for each employee. Read the content of
“Emp.txt”and display the details of each employee
Coding:
infile=open("Emp.txt",'a+')
flag=input("\n You want to update the file Y/N")
if(flag=='Y'):
n=int(input("Enter how many Employees"))
for i in range(n):
Emp_code, Emp_name,Basic_salary, DA, LIC, PF=input("Enter the Emp_code,
Emp_name, Basic_Salary, DA, LIC and PF\n").split()
Total_deductions=float(LIC)+float(PF)
Gross_salary=float(Basic_salary)+float(DA)
Net_salary=Gross_salary-Total_deductions
infile.writelines(Emp_code+" "+Emp_name+" "+str(Basic_salary)+" "+str(DA)+"
"+str(Gross_salary)+" "+str(Net_salary)+" "+str(LIC)+" "+str(PF)+"
"+str(Total_deductions)+"\n")
infile.close()
Output
Algorithm:
1. Start
2. Open the file ‘Emp.txt’ in append mode
3. Input the number of Employess
4. For every Employee, read the Emp_Code, Emp_name, Basic_Salary, DA,
Gross_Salary, Net_Salary, LIC, PF.
5. Compute the following
a. Total_deductions = LIC+PF
b. Gross_Salary = Basic_Salary+DA
c. Net_Salary = Gross_Salary – Total_deductions.
6. Write Employee’s data in to the file.
7. Close the file
8. Open the file in read mode
9. Display the details of Employee.
10. Close the file.
Coding:
class Car:
def __init__(self, year, make, speed,company,price):
self.year= year
self.make = make
self.speed = speed
self.company=company
self.price=price
def display_car_details(self):
print(str(self.year),"\t",self.make,"\t",str(self.speed),"\t",self.company,"\t",
str(self.price) )
carobject= [ ]
Output:
Algorithm:
1. Start
2. Define Variable Of Self, Year, Make, Speed, Company, Price & N
3. For I In Range N
4. Display Car Details
5. Stop
Coding:
class ARS:
def __init__(self,name,src,dest,travel_date):
self.name=name
self.src=src
self.dest=dest
self.travel=travel_date
def disp(self):
print(self.name,self.src,self.dest,self.travel_date)
l=[ ]
n=int(input("Enter how many passengers"))
for i in range(n):
print("enter details like name src dest travel date:")
n,s,d,td=input().split()
l.append(ARS(n,s,d,td))
print("Customer details travelled from bengaluru to london")
for j in range(0,len(l)):
if(l[j].src=="bengaluru"and l[j].dest=="london"):
l[j].disp()
print("Customer details from travelled from USA to china on 10/02/2020")
for j in range(0,len(l)):
if(l[j].src=="USA"and l[j].dest=="china" and l[j].travel_date=="10/02/2021"):
l[j].disp()
Algorithm:
1. Start
2. Define Variable Of Self, Name, Source, Destination, Travel_Date
3. For I In Range Airlineobject
4. Display Airlineobject Details
5. Stop
13. “Arr_1” is an integer array of size M x N. Size and content of the array is to
be read using input() by using the user defined function READ_DATA(). It is
required to display the
i. Diagonal elements of”Arr_1”
ii. Elements of mth row (row no should be entered by user)
iii. Elements of nthcolumn (column no should be entered by user)
Algorithm:
1. Start
2. Import Numpy Library
3. Define Variable Of M, N & Matrix
4. For I In Range M
5. For I In Range N
6. Read Data Of M, N, Matrix
7. Display M, N
8. Stop
Coding:
def READ_DATA(R,C,matrix):
for i in range(m):
for j in range(n):
matrix[i][j]=int(input())
import numpy
m= int(input("\n Enter the row size of M "))
n=int(input("\nEnter the columnn size of N"))
matrix=numpy.ndarray(shape=(m,n), dtype=int)
print("\n size:",matrix.size)
print("\n shape: ",matrix.shape)
print("\nDimensions:",matrix.ndim)
print("\n Enter %d elements of %dx%d matrix" %(m*n,m,n))
READ_DATA(m,n,matrix)
print("\n %dx%d matrix are:"%(m,n))
print(matrix)
print("Diagnol Elements of Matrix :")
dia=matrix.diagonal()
print(dia)
r=int(input("enter row number to display"))
print(matrix[r])
c=int(input("Enter Col number to display"))
print(matrix[:,c])
Output:
Enter the row size of M 3
size: 9
shape: (3, 3)
Dimensions: 2
14. The dictionary “Dict1” contains the pass percentage of each semester of B.
Tech in CSE, where, ” Semester” acts as the key and “Pass Percentage” acts as
the value. A Python Pandas Series is required to be implemented using the
dictionary “Dict1” and display it using a user defined function.
Algorithm:
1. Start
2. Import Pandas Libray
3. Define Variable Of Semester Name, Percentage & N
4. For I In Range N
5. Display Dictionary Using Pandas Series
6. Stop
Coding:
import pandas as pd
Btechcse_passper={ }
def Read_Dec1():
n = int(input("\n Enter Total number of semesters\n"))
for i in range(n):
print("\n Enter Semester name and Percentage")
text = input().split()
Btechcse_passper[text[0]] = text[1]
def Display_Dec1():
# create a series
stud_passper=pd.Series(Btechcse_passper)
print("\ndisplaying dictionary using pandas Series")
print(stud_passper)
print("\n the dictionary output")
print(Btechcse_passper)
Read_Dec1()
Display_Dec1()
Output:
Enter Total number of semesters
4
semester1 77.55
semester2 99.55
semester3 88.55
semester4 78.33
Viva Questions:
1. What is Python?
2. Python is an interpreted language. Explain
3. What is the difference between lists and tuples?
4. What are the Key features of Python?
5. What are Python Modules?
6. Explain Inheritance in Python with an example?
7. What are the operators of python
8. Explain in operator
9. Explain range ( ) function
10. Is python is object oriented programming language?
11. How to achive polymorphism?
12. What is encapsulation
13. What is inheritance?
14. How to achieve inheritance?
15. What is method overriding?
16. Etc..,,