0% found this document useful (0 votes)
9 views40 pages

Python Lab Manual

The Python Laboratory Manual for B. Tech II Year at REVA University outlines the vision, mission, and educational objectives of the university and the School of Computing and Information Technology. It details course objectives, lab requirements, guidelines for students, and evaluation processes, including a list of experiments and course outcomes. The manual emphasizes the development of programming skills in Python and the application of these skills to solve real-world problems.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views40 pages

Python Lab Manual

The Python Laboratory Manual for B. Tech II Year at REVA University outlines the vision, mission, and educational objectives of the university and the School of Computing and Information Technology. It details course objectives, lab requirements, guidelines for students, and evaluation processes, including a list of experiments and course outcomes. The manual emphasizes the development of programming skills in Python and the application of these skills to solve real-world problems.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

SCHOOLOFCOMPUTING AND INFORMATION

TECHNOLOGY
Programming with Python Laboratory Manual
[B22CI0305]

B. TECH II Year [III Sem]


[A.Y:2024-2025]
Python Lab Manual REVA University

INDEX
Sl.No Name Page
Number

1. Vision and Mission of the University 3

2. Vision and Mission of the School 4

3. Program Educational Objective 5

4. Program Outcome 5

5. Program Specific Outcome 6

6. Course Details 7-9


 Course Objectives
 Lab Requirement
 Guidelines to Students
 Course Outcomes
 Conduction of Practical Examination
 CO-PO-PSO Mapping
7. Lab Evaluation Process 10

8. List of Experiments 11

9. Viva Questions 40

VISION OF THE UNIVERSITY


“REVA University aspires to become an innovative university by developing excellent
human resources with leadership qualities, ethical and moral values, research culture
and innovative skills through higher education of global standards”
MISSION OF THE UNIVERSITY
 To create excellent infrastructure facilities and state-of-the-art laboratories and
incubation centers
 To provide student-centric learning environment through innovative pedagogy and
education reforms
 To encourage research and entrepreneurship through collaborations and extension
activities
 To promote industry-institute partnerships and share knowledge for innovation and
development
 To organize society development programs for knowledge enhancement in thrust areas
 To enhance leadership qualities among the youth and enrich personality traits, promote
patriotism and moral values

School of Computing and Information Technology Page 2


Python Lab Manual REVA University

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:

 PO-1: Engineering knowledge: Apply the knowledge of mathematics, science,


engineering fundamentals for the solution of complex problems in Computer Science and
Engineering.
 PO-2: Problem analysis: Identify, formulate, research literature, and analyze engineering
problems to arrive at substantiated conclusions using first principles of mathematics,
natural, and engineering sciences.
 PO-3: Design/development of solutions: Design solutions for complex engineering
problems and design system components, processes to meet the specifications with
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.
 PO-4: Conduct investigations of complex problems: Use research-based knowledge
including design of experiments, analysis and interpretation of data, and synthesis of the
information to provide valid conclusions.
 PO-5: Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modeling to complex

School of Computing and Information Technology Page 3


Python Lab Manual REVA University

engineering activities with an understanding of the limitations.


 PO-6: The engineer and society: Apply reasoning informed by the contextual knowledge
to assess societal, health, safety, legal, and cultural issues and the consequent
responsibilities relevant to the professional engineering practice.
 PO-7: Environment and sustainability: Understand the impact of the professional
engineering solutions in societal and environmental contexts, and demonstrate the
knowledge of, and need for sustainable development.
 PO-8: Ethics: Apply ethical principles and commit to professional ethics and
responsibilities and norms of the engineering practice.
 PO-9: Individual and team work: Function effectively as an individual, and as a member
or leader in teams, and in multidisciplinary settings.
 PO-10: Communication: Communicate effectively with the engineering community and
with society at large. Be able to comprehend and write effective reports documentation.
Make effective presentations, and give and receive clear instructions.
 PO-11: Project management and finance: Demonstrate knowledge and understanding of
engineering and management principles and apply these to one’s own work, as a member
and leader in a team. Manage projects in multidisciplinary environments.
 PO-12: Life-long learning: Recognize the need for, and have the preparation and ability
to engage in independent and life-long learning in the broadest context of technological
change.
Program Specific Outcomes (PSO’s)
On successful completion of the program, the graduates of B. Tech CS & SE program will be
able to:

 PSO-1: Apply the knowledge of mathematics, Computer Science and Systems


Engineering to solve complex problems in CS and SE.
 PSO-2: Analyze, design, develop solutions and conduct investigations in the domains of
database, networks and security, system software and system administration.
 PSO-3: Apply appropriate techniques, use modern programming languages, tools, and
packages for quality software development.

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:

School of Computing and Information Technology Page 4


Python Lab Manual REVA University

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

About the Lab:


Python is a general purpose, high-level programming language; other high-level
languages you might have heard of C++, PHP, Java and Python. Virtually all modern
programming languages make us of an Integrated Development Environment (IDE),
which allows the creation, editing, testing, and saving of programs and modules. In
Python, the IDE is called IDLE (like many items in the language, this is a reference to
the British comedy group Monty Python, and in this case, one of its members, Eric Idle).
Many modern languages use both processes. They are first compiled into a lower-level
language, called byte code, and then interpreted by a program called a virtual machine.
Python uses both processes, but because of the way programmers interact with it, it is
usually considered an interpreted language.

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.

Instructions to maintain the record


 Before start of the first lab they have to buy the record and bring the record to the lab.
 Regularly (Weekly) update the record after completion of the experiment and get it
corrected with concerned lab in-charge for continuous evaluation.
 In case the record is lost inform the same day to the faculty in charge and get the new
record within 2 days the record has to be submitted and get it corrected by the faculty.
 If record is not submitted in time or record is not written properly, the evaluation marks
(5M) will be deducted.

School of Computing and Information Technology Page 5


Python Lab Manual REVA University

General laboratory instructions


 Students are advised to come to the laboratory at least 5 minutes before (to the starting
time), those who come after 5 minutes will not be allowed into the lab.
 Plan your task properly much before to the commencement, come prepared to the lab with
the synopsis / program / experiment details.
 Student should enter into the laboratory with: a. Laboratory observation notes with all the
details (Problem statement, Aim, Algorithm, Procedure, Program, Expected Output, etc.,)
filled in for the lab session. b. Laboratory Record updated up to the last session
experiments and other utensils (if any) needed in the lab. c. Proper Dress code and Identity
card.
 Sign in the laboratory login register, write the TIME-IN, and occupy the computer system
allotted to you by the faculty. 5. Execute your task in the laboratory, and record the results
/ output in the lab observation note book, and get certified by the concerned faculty.
 All the students should be polite and cooperative with the laboratory staff, must maintain
the discipline and decency in the laboratory.
 Computer labs are established with sophisticated and high end branded systems, which
should be utilized properly.
 Students / Faculty must keep their mobile phones in SWITCHED OFF mode during the
lab sessions. Misuse of the equipment, misbehaviors with the staff and systems etc., will
attract severe punishment.
 Students must take the permission of the faculty in case of any urgency to go out; if
anybody found loitering outside the lab / class without permission during working hours
will be treated seriously and punished appropriately.
 Students should LOG OFF/ SHUT DOWN the computer system before he/she leaves the
lab after completing the task (experiment) in all aspects. He/she must ensure the system /
seat kept properly.

COURSE OUTCOMES (COs)


After the completion of the course, the student will be able to:

CO# Course Outcomes


Make use of language constructs to solve real world problems using
B22CI0305.1
python programming.
B22CI0305.2 Develop programs for text processing and other application domains by
making use of regular expressions.

B22CI0305.3 Apply features of object oriented and NumPy package to develop


computationally intensive programming to analyze and interpret the data.
Create data science solutions with the help of files, Pandas and Data
B22CI0305.4
Visualization.
Learn new tools and technologies in the python and apply for suitable
B22CI0305.5
application development.
Develop solutions in the python 1to the complex problems, either
B22CI0305.6 individually or as a part of the team and report the results with proper
analysis and interpretation.

School of Computing and Information Technology Page 6


Python Lab Manual REVA University

ACTIVITY MARKS

Observation(Conduction) +Viva + Modification

Record

TOTAL

Conduction of Practical Examination:


1. All laboratory experiments are included for the syllabus of practical examination.
2. Students are allowed to pick one experiment from the lot.
3. Strictly follow the instructions as printed on the cover page of answer script.
4. Marks distribution:
Conduction + Viva + Modification : __ + ___ +___ = ___ Marks
Change of experiment is allowed only once and marks allotted to the procedure part to be made
zero.

CO-PO-PSO MAPPING PSO1

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

School of Computing and Information Technology Page 7


Python Lab Manual REVA University

Lab Evaluation Process


Weekwise Evaluation Of Each Program

INTERNAL ASSESSMENT EVALUATION


(End of Semester)

Sl No ACTIVITY MARKS

01 Conduction

02 Viva Voce

03 Modification

Total

FINAL INTERNAL ASSESSMENT CALCULATION

Sl. No ACTIVITY MARKS

01 Average of weekly Entries

02 Internal Assessment Reduced to __

Total

School of Computing and Information Technology Page 8


Python Lab Manual REVA University

List of Experiments
PRACTICE:

No Title of the Experiment Tools and Expected Skill


Techniques /Ability
Part-A
Develop a program to read the student details like Name, SRN, and
input() function
1. Marks in three subjects. Display the student details, total marks and
and operators.
percentage with suitable messages.
Develop a program to implements range( ) function with
i. One parameter to print ‘n’ numbers Looping
2. ii. Two parameters to print numbers from -5 to +5
statements.
iii. Three parameters to print even numbers and odd
numbers from 1 to n.
Branching and
3. Write a program to check if the given number is Armstrong or not. looping
statements.
“LIST1” is a list that contains “N” different SRN of students read
Create and
using a user defined function with the help of input () function. It
perform
4. is required to add SRN of “M” more students that are to be
operations on
appended or inserted into “LIST1” at the appropriate place. The
list.
program must return the index of the SRN entered by user.
“TUPLE1” and “TUPLE2” are two tuples that contain “N” values of
Create and
different data types read using the user defined function “READ”
perform
5. with the help of input() function. Elements of “TUPLE1” and
operations on
“TUPLE2” are to be read one at a time and the “larger” value among
Tuples.
them should be placed into “TUPLE3”. Display all tuples.
SET1 and SET2 are two sets that contain unique integers. SET3 is to Windows Create and
be created by taking the union or intersection of SET1 and SET2 /Linux OS, perform Union
6. using the user defined function Operation (). Perform either union IDLE, and
or intersection by reading choice from user. Do not use built in Jupyter Intersection,
functions union () and intersection () and also the operators “|” and Operations on
“&“. Sets.
Create
The Dictionary “DICT1” contains N Elements and each element in
dictionary and
dictionary has the operator as the KEY and operand’s as VALUES.
7. perform
Perform the operations on operands using operators stored as
operation using
keys. Display the results of all operations.
user defined
String Operations – function.
i. A substring “Substr” between index1 and index2 is to be
extracted from the given input string “Str1”, which is read
using input(). Display the substring “Substr” using a user
defined function if available in string “Str1”, otherwise String
8. display NULL. operations.
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
Considercharacter
the text file,
and“Std.txt”,
display. with the details of students like SRN,
NAME, SEMESTER, SECTION AND AVG_MARKS. Read the file,
9. “Std.txt” and display the details of all the students of 4 th Semester File Handling.
“A” Section who have scored more than 75%.

School of Computing and Information Technology Page 9


Python Lab Manual REVA University

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.

School of Computing and Information Technology Page 10


Python Lab Manual REVA University

Part-B (Students Mini Project)

1 Library Management System

2 Hospital Management System

3 Employee Management System

4 Hotel Management System

5 Rock Paper Scissor game

6 Number guessing game

Create a Countdown Timer


7

School of Computing and Information Technology Page 11


Python Lab Manual REVA University

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 : ")

SRN = input("Enter the SRN of the student : ")

Marks1 = int(input("Enter marks in Subject 1 : "))

Marks2 = int(input("Enter marks in Subject 2 : "))

Marks3 = int(input("Enter marks in Subject 3 : "))

print("Student Details\n=========================")

print("Name :", Name)

print("SRN :", SRN)

print("Marks 1 :", Marks1)

print("Marks 2 :", Marks2)

print("Marks 3 :", Marks3)

print("Total :", Marks1+Marks2+Marks3)

print("Percent :", ((Marks1+Marks2+Marks3)/3))

School of Computing and Information Technology Page 12


Python Lab Manual REVA University

Output:

School of Computing and Information Technology Page 13


Python Lab Manual REVA University

2. Develop a program to implements range( ) function with


i. One parameter to print ‘n’ numbers
ii. Two parameters to print numbers from -5 to +5
iii. Three parameters to print even numbers and odd numbers from 1 to n

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

n=int(input("Enter the value of n"))

for i in range(n+1):

print( i , end=' ')

Output:

ii. Range function with two parameter

for i in range(-5 , 6):

print( i , end=' ')

Output:

School of Computing and Information Technology Page 14


Python Lab Manual REVA University

iii. Range function with three parameter

n=int(input("Enter the value of n"))

print("Even numbers are:")

for i in range(2 , n+1 , 2):

print( i , end=' ')

Output:

n=int(input("Enter the value of n"))

print("Odd numbers are:")

for i in range(1 , n+1 , 2):

print( i , end=' ')

Output:

School of Computing and Information Technology Page 15


Python Lab Manual REVA University

3. Write a program to check if the given number is Armstrong or not.

An Armstrong number is a number that is equal to the sum of the cubes (for 3 digit number)
of its own digits.

Example – 153, 370, 371, 407

153 = 1^3+5^3+3^3 = 153 is an Armstrong number.

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

while temp > 0:

digit = temp % 10

sum = sum+ (digit * digit * digit)

temp = temp//10

if sum==num:

print('It is an Armstrong number')

else:

print('It is not an Armstrong number')

School of Computing and Information Technology Page 16


Python Lab Manual REVA University

Output:

School of Computing and Information Technology Page 17


Python Lab Manual REVA University

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:

1. Create an empty list named as list1

2. Read the value of n or m

3. Append or store or adding the elements to the list until n or m

4. Increment i by 1 until n or m

5. Display the list1

6. Repeat the step 2-5

7. Read the index value and display the value

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))

School of Computing and Information Technology Page 18


Python Lab Manual REVA University

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

School of Computing and Information Technology Page 19


Python Lab Manual REVA University

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:

1. Create an empty tuple named as tuple1


2. Display the empty tuple
3. Add value to the tuple 1
4. Create another tuple2 and add values
5. Display the maximum stored values in tuple1 and tuple2

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)

School of Computing and Information Technology Page 20


Python Lab Manual REVA University

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()))

n2=int(input("Enter length of set2"))


for i in range(n2):
s2.add(int(input()))
print("S1:",s1)
print("S2:",s2)

#Code to give choice for user


print("ENTER YOUR CHOICE: 1. UNION 2. INTERSECTION")
ch=int(input( ))
if ch==1:
uni( )
elif ch==2:
inter( )
else:
print(“INVALID CHOICE”)

School of Computing and Information Technology Page 21


Python Lab Manual REVA University

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

School of Computing and Information Technology Page 22


Python Lab Manual REVA University

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

School of Computing and Information Technology Page 23


Python Lab Manual REVA University

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:

dict1={ '+' : [ 10 , 20 ] , '-' : [ 50 , 40 ] , '*' : [ 30 , 2 ] , '/' : [ 10 , 2 ] }


i=0
def add( ):
a=dict1["+"]
print ("Addition of ",a,"is:")
print(a[i]+a[i+1])

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")

School of Computing and Information Technology Page 24


Python Lab Manual REVA University

Output

Algorithm:

1. Create directories with key and values with zip() function


2. Assign directories dict to sampleDict
3. Display SampleDict
4. Create two directories dict1 and dict 2 : Assign key and values
5. Merge dict3 = {**dict1, **dict2}
6. Display dict 3
7. Perform Copy , update , remove and rename the directories key and values
8. Repea step 6 after each function applied on dict3

School of Computing and Information Technology Page 25


Python Lab Manual REVA University

8. i. A substring “Substr” between index1 and index2 is to be extracted from the


given input string, “Str1”, which is read using input() and display the
substring “Substr” using a user defined function if available in string “Str1”,
otherwise display NULL.

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:

Str1=input(“enter your string\n”)

def substr1( ):

index1=int(input(“enter index1: ”))

index2=int(input(“enter index2: ”))

substring=Str1[index1:index2]

print(“Substring extracted from {} to {} is {}”.format(index1,index2,substring))

substr1( )

Output

enter your string


reva university
enter index1: 1
enter index2: 4
Substring extracted from 1 to 4 is eva

School of Computing and Information Technology Page 26


Python Lab Manual REVA University

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.

a) Convert all the strings to uppercase

Algorithm:
1. Read the input from the user
2. Use upper() function on the input.
3. Use split() function on the input

Coding:

s=input("Tell me about yourself\n")


print("You Told:",s.upper())

Output
Tell me about yourself
i am ramu from bangalore
You Told: I AM RAMU FROM BANGALORE

b) Split the words of a string using space as the separation character.

s=input("Tell me about yourself\n")


print("You Told:",s.upper( ))
print("Elements of your string:",s.split( ))

Output
Tell me about yourself

i am ramu from bangalore

You Told: I AM RAMU FROM BANGALORE

Elements of your string: ['i', 'am', 'ramu', 'from', 'bangalore']

School of Computing and Information Technology Page 27


Python Lab Manual REVA University

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:

1. Open the file in append mode


2. Input the number of students
3. For every student, read the SRN, name, semester, section and avg_marks.
4. Write student’s data in to the file.
5. Close the file
6. Open the file in read mode
7. Display the details of sudents , if average mark >75 && section ==’A’
8. Close the file.

Coding:

# Code to add student data into file


infile=open("E:/file1.txt",'a+')
flag=input("\n You want to update the file Y/N")
if(flag=='Y'):
n=int(input("Enter how many students"))
for i in range(n):
srn,name,sem,sec,avg_mark=input("Enter the SRN number,name, semester,section and
average mark of the student\n").split()
infile.writelines(srn+" "+name+" "+sem+" "+sec+" "+avg_mark+"\n")
infile.close( )
# code to extract 'A' section students with 75% above
print("The content of student file are")
mylines=[ ]
outfile=open('E:/file1.txt','r+')
for i in outfile:
mylines.append(i.split())
for element in mylines:
avgmark=int(element[-1])
sec=str(element[-2])
if(avgmark >= 75 and sec=='A'):
print(element)
outfile.close( )
School of Computing and Information Technology Page 28
Python Lab Manual REVA University

Output:

File1.txt (saved in E drive)

School of Computing and Information Technology Page 29


Python Lab Manual REVA University

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()

print("\nEmployee details Emp_code, Emp_name, Basic_Salary, DA,Gross_salary,


Net_salary, LIC and PF, Total_deductions are\n")
outfile=open("Emp.txt",'r+')
for element in outfile:
print(element)
outfile.close()

School of Computing and Information Technology Page 30


Python Lab Manual REVA University

Output

Emp.txt in E drive looks like below –

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.

School of Computing and Information Technology Page 31


Python Lab Manual REVA University

11. 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 operations:
i) Get the details of “Car” object from user and store into Array of objects
ii) Display the details of “Car” object based on “Company”, “Model” and
“Price”.

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= [ ]

n=int(input("\n How many car details you want "))


for i in range(n):
year=input("\n Enter car Model")
make=input("\nEnter Car make")
speed=float(input("\nEnter the speed of Car"))
company=input("\nEnter company name")
price=float(input("\nEnter the price of car"))
carobject.append(Car(year,make,speed,company,price))

print("\n The Car model make speed-KMPL company price L/Crore\n")


for obj in carobject:
obj.display_car_details()

Output:

School of Computing and Information Technology Page 32


Python Lab Manual REVA University

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

School of Computing and Information Technology Page 33


Python Lab Manual REVA University

12. Airline Reservation System contains the attributes of passengers such as


Name, PAN-No., Mobile-no, Email-id, Source, Destination, Seat-No and Air-
Fare, Travel_date. A Class is required to be created for “Airlilne” with the
above attributes and perform the following operations:
a. Get the details of “Airline” object from user and store into Array of
objects
b. List details of all the passengers who travelled From “Bengaluru to
London”.
c. List details of all the passengers who travelled From “USA to China”
on 10th of Feb, 2020.

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()

School of Computing and Information Technology Page 34


Python Lab Manual REVA University

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

School of Computing and Information Technology Page 35


Python Lab Manual REVA University

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])

School of Computing and Information Technology Page 36


Python Lab Manual REVA University

Output:
Enter the row size of M 3

Enter the columnn size of N3

size: 9

shape: (3, 3)

Dimensions: 2

Enter 9 elements of 3x3 matrix


10
20
30
40
50
60
70
80
90

3x3 matrix are:


[[10 20 30]
[40 50 60]
[70 80 90]]

Diagnol Elements of Matrix :


[10 50 90]

enter row number to display 1


[40 50 60]

Enter Col number to display 2


[30 60 90]

School of Computing and Information Technology Page 37


Python Lab Manual REVA University

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()

School of Computing and Information Technology Page 38


Python Lab Manual REVA University

Output:
Enter Total number of semesters
4

Enter Semester name and Percentage

semester1 77.55

Enter Semester name and Percentage

semester2 99.55

Enter Semester name and Percentage

semester3 88.55

Enter Semester name and Percentage

semester4 78.33

Displaying dictionary using pandas Series


semester1 77.55
semester2 99.55
semester3 88.55
semester4 78.33
dtype: object

The dictionary output


{'semester1': '77.55', 'semester2': '99.55', 'semester3': '88.55', 'semester4': '78.33'}

School of Computing and Information Technology Page 39


Python Lab Manual REVA University

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..,,

School of Computing and Information Technology Page 40

You might also like