PP Lab Manual
PP Lab Manual
Vision
To meet the emerging trends in computer Science and Engineering,
strive for self-reliance enabled through high end research by adapting a
futuristic approach.
Mission
To impart qualitative education, prepare students refurbish their latent
talents and aspire for a pragmatic career in Computer Science and
Engineering
To provide an ambiance to develop strategic areas of advance study
with perception to foster industry centric education in computer
science and Engineering.
To Inculcate self-learning among students to make them self-reliant
and socially responsible.
Course objectives:
Student will:
1. To implement Basic input /output operations with various Data Types supported by
python.
2. To develop functions for code reusability and experiment string manipulation
operations with the use of inbuilt functions.
3. To Create a python program for experimenting list, tuple and dictionary
4. To demonstrate Class and objects to make use of object oriented programming
concepts.
5. To Implement File handling operations to access the contents of file
Course outcomes:
Students will be able to:
1. Apply Basic input /output operations for working with different data types in python.
2. Design functions for achieving code reusability and string manipulations.
3. Create a python program for list, tuple dictionary
4. Demonstrate Class and objects
5. Implement File handling operations
EXPERIMENT 1.
i. Write a python program to obtain user input data (int, float, string) and display.
ii. Write a python program to find the roots of a quadratic equation
iii. Write a python program to perform arithmetic operations (+, -, *, /, %) for given input
values and printout the result values.
EXPERIMENT 2.
i. Write a python programs that use both recursive and non-recursive functions to find the
factorial of a given integer
ii. Operators and Operands in Python: (Arithmetic, relational and logical operators),
operator precedence, Expressions and Statements.
iii. (Assignment statement); Taking input (using raw input () and input ()) and displaying
output (print statement); Putting Comments.
EXPERIMENT 3.
i. Write python programs to perform operation on Strings using following functions: len,
capitalize, find, isalnum, isalpha, isdigit, lower, islower, isupper, upper, lstrip, rstrip,
isspace, istitile, partition, replace, join, split, count, decode, encode, swapcase.
ii. Enter the details of 5 students and display the details sequentially.
EXPERIMENT 4.
i. Write python programs to perform List operators: (joining, list slices)
ii.Write python programs to perform List functions: len, insert, append, extend, sort, remove,
and reverse, pop.
iii. Write python programs to check whether the string is palindrome or not?
EXPERIMENT 5.
i. Write python programs to perform Tuple functions: cmp(), len(), max(), min(), tuple()
EXPERIMENT 10. Write a python script to perform various FILE handling operations.
Open, close, read, write, copy.
EXPERIMENT 11.
i) Write a python script to connect to the database and perform DDL operations.
ii) Create table, insert data into table and display the table data.
EXPERIMENT 12. Write a python script to connect to the database and perform various DML
and DQL operations.
Text Books:
1. Programming in Python 3- A complete Introduction to the Python Language- Second
Edition, Mark Summerfiels, Addison-Wesley 2010.
2. Programming Python- 4th Edition, Mark Lutz, O’Reilly, 2011.
Reference Books
1. Object-Oriented Programming in Python, Michael H, Goldwasser, David Letscher,
Pearson Prentice Hall, 2008
PYTHON
PSO
PSO
PO1
PO2
PO3
PO4
PO5
PO6
PO7
PO8
PO9
PO1
PO1
PO1
0
2
PROGRAMMING Lab
Apply Basic
input /output
operations for
CO1 3 2 2 1 2 2 2 1 2
working with
different data
types in python.
Design functions
for achieving
CO2 code reusability 3 2 3 2 2 2 2
and string
manipulations.
Create a python
program for
CO3 implementing 3 2 2 3 2 2 2 1 2
list, tuple
dictionary.
Demonstrate
CO4 Class and objects 3 2 1 2 2 2 2 2 3
6.Lab Manual
EXPERIMENT -1
1 Write a python program to obtain user input data (int, float, string)
and display.
OUT PUT:
enter an integer :5
enter an string :sat
enter an float value :2.5
('you have entered integer as :', 5)
('you have entered string as :', 'sat')
('you have entered float value as :', 2.5)
import math
if d < 0:
print ("This equation has no real solution");
elif d == 0:
e = (-b+math.sqrt(b**2-4*a*c))/2*a
print ("This equation has one solutions: ", e);
else:
f = (-b+math.sqrt(b**2-4*a*c))/2*a
g = (-b-math.sqrt(b**2-4*a*c))/2*a
OUT PUT:
OUT PUT:
enter the 1st no :2
enter the 2nd no :3
('addition is :', 5.0)
('multiplication is :', 6.0)
('division is :', 0.6666666666666666)
('substraction is :', -1.0)
('modulo is :', 2)
EXPERIMENT -2
Recursive:-
def factorial(n):
if n==1:
return 1
else:
return n * factorial(n-1)
Non Recursive:-
OUT PUT:
Enter a number: 5
('The factorial of', 5, 'is', 120)
print("addition :",a+b);
print("substraction :",a-b);
OUT PUT:
OUT PUT:
OUT PUT:
OUT PUT:
EXPERIMENT -4
Output:
C:\python>python listopr.py
enter your first name :asha
output:
C:\python>python listslice.py
enter data for a0 :1
enter data for a1 :2
enter data for b0 :5
enter data for b1 :6
enter data for c0 :7
enter data for c1 :9
Result {(a0,b0,c0),(a1,b1,c1)} : (1, 5, 7, 2, 6, 9)
total list of a,b,c : [[1, 2], [5, 6], [7, 9]]
slice by c0,c1 value from List : [7, 9]
output:
C:\python>python listfun.py
enter the element into list1 as l1 : 1
enter the element into list2 as l2 : 2
list1 : [1, 2]
length of the list : 2
enter the index to insert the element : 1
enter the value : 3
Now list1 is : [1, 3, 2]
output:
C:\python>python palin.py
Enter a string : asha
asha : It is not palindrome
C:\python>python palin.py
Enter a string : madam
madam : It is palindrome
EXPERIMENT -5
output:
C:\python>python tupfun.py
output:
C:\python>python tuple.py
enter a word for Tuple:sam
enter a word for Tuple:jam
enter a word for Tuple:ram
enter the word which you want to search :ram
ram found
C:\python>python tuple.py
enter a word for Tuple:sat
enter a word for Tuple:mat
enter a word for Tuple:fat
enter the word which you want to search :sam
sam not found
value = "1234567890"
pairs = []
for i in range(1, len(value), 2):
one = value[i - 1]
two = value[i]
pairs.append((one, two))
# Display list of tuple pairs.
for pair in pairs:
print(pair)
output:
C:\python>python pair.py
('1', '2')
('3', '4')
('5', '6')
('7', '8')
('9', '0')
EXPERIMENT- 6
1 Dictionary functions & Methods: cmp, len, clear(), get(), has_key(),
items(), keys(), update(), values() .
2 person={"name": 'Ram', "age": 23, "gender": 'male'};
3 print("content of the dictionary variable person is :",person);
4 print("length of the dictionary variable person : ",len(person))
5 person.clear()
6 print("after clearing the person, length is :", len(person))
7
output:
C:\python>python ex6.1.py
content of the dictionary variable person is : {'name': 'Ram', 'age': 23, 'gender':
'male'}
length of the dictionary variable person : 3
after clearing the person, length is : 0
the content of dictionary variable var1 : {'A': 2, 'B': 4, 'C': 6}
the key of var1 : dict_keys(['A', 'B', 'C'])
the items are : dict_items([('A', 2), ('B', 4), ('C', 6)])
the value of A is : 2
Value : {'A': 2, 'B': 4, 'C': 6, 'D': 8}
values of var1 are : dict_values([2, 4, 6, 8])
2 Create a list of animal using dictionary variable “animal” and find
out if the specific animal present in the list or not?
animals = {}
animals["monkey"] = 1
animals["tuna"] = 2
animals["giraffe"] = 4
print(animals);
# Use in.
if "tuna" in animals:
print("tuna is present.")
else:
print("No tuna")
output:
C:\python>python ex6.2.py
{'monkey': 1, 'tuna': 2, 'giraffe': 4}
tuna is present.
No elephant
EXPERIMENT- 7
1. Write a python program to create a class, its objects and accessing
attributes.
class Student:
def __init__(self, name, roll):
self.name = name
self.roll = roll
def showStudent(self):
print ("Name is : ", self.name)
print("Roll No : ", self.roll)
output:
C:\python>python ex7.1.py
Enter Name :asha
Enter Roll No :01
Enter Name :jyothi
Enter Roll No :02
Name is : asha
Roll No : 01
Name is : jyothi
Roll No : 02
2. Create a Customer class and check the balance and withdraw and
deposit some amount.
class Customer:
def __init__(self, name, balance):
self.name = name
self.balance = balance
def withdraw(self, amount):
if amount > self.balance:
print("error");
else:
self.balance = self.balance - amount
def deposit(self, amount):
self.balance += amount
def show(self):
print("Avilable balance is : ",self.balance);
output:
C:\python>python ex7.2.py
Enter The Customer Name :Ram
Enter The Ammount :20000
Avilable balance is : 20000
How much amount u want to withdraw : 10000
Avilable balance is : 10000
How much amount u want to deposit : 50000
Avilable balance is : 60000
EXPERIMENT- 8
1. Write a python script to implement exception handling. Check whether
the input no is integer or not.
while True:
try:
n =int(input("Please enter an integer: "))
break
except ValueError:
print("No valid integer! Please try again ...")
output:
C:\python>python ex8.1.py
Please enter an integer: a
No valid integer! Please try again ...
Please enter an integer:
3. while True:
4. try:
5. num = int(input("Your Dividend: "))
6. x = int(input("Your Divisor : "))
7. div = num / x
8. except ValueError:
9. print("You should have given an int value ")
10. except ZeroDivisionError:
11. print("Infinity")
12. else:
output:
C:\python>python ex8.2.py
Your Dividend: 9
Your Divisor : 3
Result: 3.0
finally exception handeled..
C:\python>python ex8.2.py
Your Dividend: 5
Your Divisor : 2
Result: 2.5
finally exception handeled..
EXPERIMENT -9
class Polygon:
def __init__(self, no_of_sides):
self.n = no_of_sides
self.sides = [0 for i in range(no_of_sides)]
def inputSides(self):
self.sides = [float(input("Enter side "+str(i+1)+" : ")) for i in
range(self.n)]
def dispSides(self):
class Triangle(Polygon):
def __init__(self):
Polygon.__init__(self,3)
def findArea(self):
a, b, c = self.sides
# calculate the semi-perimeter
s = (a + b + c) / 2
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print('The area of the triangle is %0.2f' %area)
t = Triangle()
t.inputSides()
t.dispSides()
t.findArea()
output:
C:\python>python ex9.py
Enter side 1 : 3
Enter side 2 : 5
Enter side 3 : 4
Side 1 is 3.0
Side 2 is 5.0
Side 3 is 4.0
The area of the triangle is 6.00
EXPERIMENT 10
PYTHON LAB Manual CSE AIML ,JBIET. Page 29
1 .Python script to create a File file.txt
file = open("file.txt", "w")
file.write("data inside file.")
# Close opend file
file.close()
output:
C:\python>python fo.name.py
Read String is : Python is
Current file position : 10
Again read String is : Python is
EXPERIMENT 11
1. The following Python script is used for establishing the connection to Mysql Database.
import mysql.connector
# Open database connection
conn =mysql.connector.connect(host='localhost',
password='sHj@6378#jw',user='root')
if conn.is_connected():
print("connection established....")
import MySQLdb
cursor.execute(sql)
import MySQLdb
import MySQLdb
import MySQLdb
Update Operation
2. The following procedure updates all the records having SEX as 'M'. Here, we increase AGE of
import MySQLdb
3. Following is the procedure to delete all the records from EMPLOYEE where AGE is more than
20
import MySQLdb
Experiment-1
Experiment-2
Experiment-3
Experiment-4
Experiment-5
Experiment-6
Experiment-7
Experiment-8
Experiment-9
Experiment-10
Experiment-11
Experiment-12