0% found this document useful (0 votes)
4 views38 pages

PP Lab Manual

The document outlines the vision, mission, program educational objectives (PEOs), program outcomes (POs), and course objectives and outcomes for a Computer Science and Engineering program focused on Python programming. It details various experiments and practical exercises to be conducted in the Python lab, including input/output operations, data structures, object-oriented programming, and file handling. Additionally, it includes a mapping of course outcomes to program outcomes and specific outcomes, along with references for textbooks and resources.

Uploaded by

nainalashalini
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views38 pages

PP Lab Manual

The document outlines the vision, mission, program educational objectives (PEOs), program outcomes (POs), and course objectives and outcomes for a Computer Science and Engineering program focused on Python programming. It details various experiments and practical exercises to be conducted in the Python lab, including input/output operations, data structures, object-oriented programming, and file handling. Additionally, it includes a mapping of course outcomes to program outcomes and specific outcomes, along with references for textbooks and resources.

Uploaded by

nainalashalini
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 38

1.

Vision, Mission & PEOs

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.

PYTHON LAB Manual CSE AIML ,JBIET. Page 1


2. POs & PSOs
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Program Educational Objectives (PEOs):


To bring out physical, analytical and computational methods of
computer science and engineering realize the challenges through
PEO1 abstracting and essential structure, identifying causes of uncertainity,
introducing relevant models, tools enabling for evaluation to develop
suitable solution.
To mould the students career through steering their confidence levels
for better understanding, strengthening technical outlook for
PEO2
innovation and better communication at the job place where they are
employed.
To hone the technical skills for creating and productivity in computer
PEO3
science and engineering beyond class room learning.
To promote multi disciplinary awareness through exposure to areas of
PEO4 project development and industrial training for sustainable
competition in Research and Development.

Program Outcomes of CSE Department (POs):

Engineering Knowledge: Apply the knowledge of mathematics,


PO1 Engineering and Science whose basic components in compliance
with a chosen area of specialization leading to answer complex
problems in Engineering.
Problem Analysis: Identify, formulate, research literature and
PO2 analyze complex engineering problems reaching substantiated
conclusions using first principles of mathematics, natural sciences
and engineering sciences.
Design / Development of Solutions: Design solutions for
complex engineering problems besides designing system
PO3
components or processes that meet specified needs with emphasis
on public health and safety, cultural, societal and environmental
aspects.
Conduct investigations of complex problems: using research-
PO4 based knowledge and research methods including design of
experiments, analysis and interpretation of data and synthesis of
information to provide valid conclusions.

PYTHON LAB Manual CSE AIML ,JBIET. Page 2


PO5 Modern Tool Usage: Create, select and apply appropriate
techniques, resources and modern engineering and IT tools
including prediction and modeling to complex engineering activities
being aware of the limitations.
PO6 The Engineer and Society: Apply reasoning accomplished
through contextual knowledge to assess societal, health, safety,
legal and cultural issues and the consequent responsibilities
relevant to professional engineering practice.
PO7 Environment and Sustainability: Understand impact of
Engineering g solution towards societal and environmental context
and demonstrate the necessity for sustainable development.
PO8 Ethics: Apply ethics principles adhere to practice while discharging
responsibilities within the norms of engineering practice.
PO9 Individual and Team Work: Function with efficacy as an
individual, member or take the lead in diverse teams and in multi-
disciplinary settings.
PO10 Communication: Make effective communication with the fraternity
at large to enhance the ability to comprehend and write project
report and draft documents, set on the presentations in an
appealing manner. Have instruction clarity in receiving and giving.
PO11 Project Management and Finance: Demonstrate knowledge with
an understanding on engineering and management principles and
comply with ones own work, as a member and leader of a team, to
manage projects and apply in multidisciplinary environments.
PO12 Life-long Learning: Recognize the need to have preparation and
capability to engage in independent and life- long learning in the
broadest context of technological change. Any signatory needs to
provide an overview of its learning outcomes and confirm the
compliance with programs.

Program Specific Outcomes (PSOs):


PSO1 Ability to design and develop computing system using
mathematical customs outcomes other discipline to meet business
objectives.

PSO2 Ability to test and analyze quality of various systems to integrate


them in larger computer systems.

PYTHON LAB Manual CSE AIML ,JBIET. Page 3


3. Course objectives & Course outcomes

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

PYTHON LAB Manual CSE AIML ,JBIET. Page 4


4. Course Syllabus / List of Experiments
(Syllabus Copy)

J.B.INSTITUTE OF ENGINEERING & TECHNOLOGY


UGC AUTONOMOUS
B.Tech. CSE (AI-ML) L T-P-D C
II Year - II Semester 0 0-3-0 2
PYTHON PROGRAMMING LAB

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

PYTHON LAB Manual CSE AIML ,JBIET. Page 5


ii. Write python programs to check whether the word is present in the tuple or not?
iii. Write python programs to Take a string as (“1234567890”) and create a pair {(1,2),(3,4),
(5,6),(7,8),(9,0)} using tuple.
EXPERIMENT 6.
i. Write python programs to perform Dictionary functions & Methods: cmp, len, clear(),
get(), has_key(), items(), keys(), update(), values() .
ii. Write python programs to Create a list of animal using dictionary variable “animal” and
find out if the specific animal present in the list or not?
EXPERIMENT 7.
i) Write a python program to create a class, its objects and accessing attributes.
ii) Create a Customer class and check the balance and withdraw and deposit some amount.

EXPERIMENT 8. Write a python script to implement exception handling.


i. Check whether the input no is integer or not.
ii. Handel the exceptions that are come at the time of division.

EXPERIMENT 9. Write a python script to perform inheritance.

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 LAB Manual CSE AIML ,JBIET. Page 6


5. CO & PO Mapping

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

PYTHON LAB Manual CSE AIML ,JBIET. Page 7


Implement File
CO5 handling 3 2 2 2 2 2 2 1 3
operations
3 2 1.7 2.2 2 2 2 1.4 2.4
AVERAGE 5

6.Lab Manual

EXPERIMENT -1

1 Write a python program to obtain user input data (int, float, string)
and display.

a=int(input("enter an integer :"));


b=input("enter an string :");
c=float(input("enter an float value :"));

print("you have entered integer as :", a)


print("you have entered string as :",b);

PYTHON LAB Manual CSE AIML ,JBIET. Page 8


print("you have entered float value as :",c);

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)

2 . Write a python program to find the roots of a quadratic equation.

import math

a=float(input("Enter the value of 'a' :"))


b=float(input("Enter the value of 'b' :"))
c=float(input("Enter the value of 'c' :"))
d = b**2-4*a*c

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

PYTHON LAB Manual CSE AIML ,JBIET. Page 9


print ("This equation has two solutions: ", f, " and", g);

OUT PUT:

Enter the value of 'a' :1


Enter the value of 'b' :5
Enter the value of 'c' :3
('This equation has two solutions: ', -0.6972243622680054, ' and', -
4.302775637731995)

3 Write a python program to perform arithmetic operations (+, -, *, /, %)


for given input values and printout the result values.

a=float(input("enter the 1st no :"));


b=float(input("enter the 2nd no :"));
c=a+b;
d=a*b;
e=a/b;
f=a-b;
g=int(a%b);
print("addition is :",c);
print("multiplication is :",d);
print("division is :",e);
print("substraction is :",f);

PYTHON LAB Manual CSE AIML ,JBIET. Page 10


print("modulo is :",g);

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

1 .Write a python programs that use both recursive and non-recursive


functions to find the factorial of a given integer.

Recursive:-

def factorial(n):
if n==1:
return 1
else:
return n * factorial(n-1)

PYTHON LAB Manual CSE AIML ,JBIET. Page 11


print(factorial(int(input("enter the no : "))))

Non Recursive:-

num = int(input("Enter a number: "))


factorial = 1
if num < 0:
print("Sorry, factorial does not exist for
negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i

print("The factorial of",num,"is",factorial)

OUT PUT:
Enter a number: 5
('The factorial of', 5, 'is', 120)

2 .Operators and Operands in Python: (Arithmetic, relational and


logical Operators), operator precedence, Expressions and
Statements.

a = int(input("enter the 1st no 'a' : "))


b = int(input("enter the 2nd no 'b' : "))

print("some arithmatic operations..")

print("addition :",a+b);
print("substraction :",a-b);

PYTHON LAB Manual CSE AIML ,JBIET. Page 12


print("multiplication :",a*b);
print("division :",a/b);

print("some relational and Logical operations..")

if(a!=0 & a<100):


print("number 'a' is in betwwen 0 to 100");
else:
print("number 'a' is greater than 100");
if(b==0 | b<a):
print("number 'b' is smaller num.");
else:
print("number 'b' is greater than num 'a'");

OUT PUT:

enter the 1st no 'a' : 2


enter the 2nd no 'b' : 4
some arithmatic operations..
('addition :', 6)
('substraction :', -2)
('multiplication :', 8)
('division :', 0)
some relational and Logical operations..
number 'a' is in betwwen 0 to 100
number 'b' is greater than num 'a'

3. (Assignment statement); Taking input (using raw input () and


input ()) and displaying output (print statement); Putting
Comments.

PYTHON LAB Manual CSE AIML ,JBIET. Page 13


# hello statement.

b=input("enter your gender : ")


a=input("enter your name : ")
c=str(b);
if(c=="m" or c=="male"):
print("Hello Mr.",a)
elif(b=="f" or b=="female"):
print("Hello Miss. ",a);
else:
print("Hello");

OUT PUT:

enter your gender : female


enter your name : Asha
('Hello Miss.', 'Asha')
EXPERIMENT -3
1 Strings : len, capitalize, find, isalnum, isalpha, isdigit, lower, islower,
isupper, upper, lstrip, rstrip, isspace, istitile, partition, replace, join,
split, count, decode, encode, swapcase.

a=input("enter the 1st string : ")


b=input("enter the 2nd String : ")
print("length of the 2nd string is : ",len(b))
print ("length of the 1st string is : ",len(a))
print ("1st string in capital letter : ",a.capitalize())
print ("1st string in capital letter : ",b.capitalize())
b = input("enter the finding String : ")
print ("your given string starts from ",(a.find(b)+1),"
position.")
a=input("first string in lowercase :")
print( "length of the 1st string is : ",a.islower())
d="sam101"

PYTHON LAB Manual CSE AIML ,JBIET. Page 14


print(d.isalnum())

OUT PUT:

enter the 1st string : asha


enter the 2nd String : jyothi
length of the 2nd string is : 6
length of the 1st string is : 4
1st string in capital letter : Asha
1st string in capital letter : Jyothi
enter the finding String : as
your given string starts from 1 position.
first string in lowercase :ha
length of the 1st string is : True
True

2.Enter the details of 5 students and display the details sequentially.

n=int(input("enter the no. of students:"));


for x in range(0,n):
name=input("enter the name of student:")
rollno=input("enter the rollno of the student:")
age=input("enter the age of the student:")
print("name:",name);
print("rollno:",rollno);
print("age:",age);
print("thank you....!!!!")

OUT PUT:

enter the no. of students:2


enter the name of student:sanju
enter the rollno of the student:501

PYTHON LAB Manual CSE AIML ,JBIET. Page 15


enter the age of the student:26
('name:', 'sanju')
('rollno:', 501)
('age:', 26)
enter the name of student:prem
enter the rollno of the student:506
enter the age of the student:25
('name:', 'prem')
('rollno:', 506)
('age:', 25)
thank you....!!!!

EXPERIMENT -4

1. Write a python programs List operators: (joining, list slices)


fname=input("enter your first name :");
mname=input("enter your middle name :");
lname=input("enter your last name :");
str =input("enter any separator(!@#$%^&*) :");
seq = (fname,mname,lname);
print("Given person name is :",str.join( seq ));

Output:
C:\python>python listopr.py
enter your first name :asha

PYTHON LAB Manual CSE AIML ,JBIET. Page 16


enter your middle name :jyothi
enter your last name :sabnekar
enter any separator(!@#$%^&*) :@
Given person name is : asha@jyothi@sabnekar

List Slices Method:

a0=int(input("enter data for a0 :"))


a1=int(input("enter data for a1 :"))
b0=int(input("enter data for b0 :"))
b1=int(input("enter data for b1 :"))
c0=int(input("enter data for c0 :"))
c1=int(input("enter data for c1 :"))
A = [a0,a1];
B = [b0,b1];
C = [c0,c1];
set1=sum(zip(A,B,C),())
print("Result {(a0,b0,c0),(a1,b1,c1)} : ",set1);
l1=[A,B,C]
print("total list of a,b,c : ",l1);
print("slice by c0,c1 value from List : ",l1[2]);

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]

2. List functions: len, insert, append, extend, sort, remove, and

PYTHON LAB Manual CSE AIML ,JBIET. Page 17


reverse, pop

l1=int(input("enter the element into list1 as l1 : "))


l2=int(input("enter the element into list2 as l2 : ") )
list1=[l1,l2];
print("list1 : ",list1);
print("length of the list : ",len(list1));
i=int(input("enter the index to insert the element : "))
v=int(input("enter the value : "))
list1.insert(i,v)
print("Now list1 is : ",list1);
v1=int(input("enter the element to list which append at the last : "))
list1.append(v1);
print("Now list1 is : ",list1);
#print("Now list is in sorted order : ",list1.sort());
l21=int(input("enter the element into list2 as l1 : "))
l22=int(input("enter the element into list2 as l2 : ") )
list2 =[l21,l22]
print("list2 is : ",list2);
list1.extend(list2)
print("the given extended list is : ",list1);
d=int(input("enter the value to delete from list1 : "))
list1.remove(d);
print("Now list1 is : ",list1);
list1.reverse()
print("now list is in reverse order : ",list1);
print("Now list1 is : ",list1);
p=int(input("enter the index to pop the element : "))
print("The element which is poped from List1 : ", list1.pop(p));

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]

PYTHON LAB Manual CSE AIML ,JBIET. Page 18


enter the element to list which append at the last : 4
Now list1 is : [1, 3, 2, 4]
enter the element into list2 as l1 : 11
enter the element into list2 as l2 : 22
list2 is : [11, 22]
the given extended list is : [1, 3, 2, 4, 11, 22]
enter the value to delete from list1 : 3
Now list1 is : [1, 2, 4, 11, 22]
now list is in reverse order : [22, 11, 4, 2, 1]
Now list1 is : [22, 11, 4, 2, 1]
enter the index to pop the element : 2
The element which is poped from List1 : 4

3. Check whether the string is palindrome or not?


str = input("Enter a string : ")
rev_str = reversed(str)
if list(str) == list(rev_str):
print(str, ": It is palindrome")
else:
print(str, ": It is not palindrome")

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

1 Tuple functions: cmp(), len(), max(), min(), tuple()


2 t1=input("enter 't1' value for tuple1:");
3 t2=input("enter 't2' value for tuple2:");
4 t3=input("enter 't3' value for tuple3:");

PYTHON LAB Manual CSE AIML ,JBIET. Page 19


5 tuple1=(t1,t2,t3);
6 print("tuple1 is:",tuple1);
7 print("length of tuple1 is:",len(tuple1))
8 print("max element of tuple1 is :",max(tuple1))
9 print("min element of tuple1 is:",min(tuple1))
10 t11=input("enter 't1' value for tuple2:");
11 t12=input("enter 't2' value for tuple2:");
12 t13=input("enter 't3' value for tuple2:");
13 tuple2=(t11,t12,t13);
14 print("tuple2 is:",tuple2);
15 if tuple1 < tuple2:
16 print("tuple1 is less than tuple2")
17 else:
18 print("tuple1 is greater than or equal to tuple2")
19 tuple3=tuple(tuple2)
20 print("after assign tuple2 to tuple3,tuple3 is:",tuple3);

output:

C:\python>python tupfun.py

enter 't1' value for tuple1:asha

enter 't2' value for tuple2:jyothi

enter 't3' value for tuple3:sabnekar

tuple1 is: ('asha', 'jyothi', 'sabnekar')

length of tuple1 is: 3

max element of tuple1 is : sabnekar

min element of tuple1 is: asha

enter 't1' value for tuple2:a

PYTHON LAB Manual CSE AIML ,JBIET. Page 20


enter 't2' value for tuple2:j

enter 't3' value for tuple2:s

tuple2 is: ('a', 'j', 's')

tuple1 is greater than or equal to tuple2

after assign tuple2 to tuple3,tuple3 is: ('a', 'j', 's')

2 Check whether the word is present in the tuple or not?


3 t1=input("enter a word for Tuple:");
4 t2=input("enter a word for Tuple:");
5 t3=input("enter a word for Tuple:");
6 pair = (t1,t2,t3)
7 w=input("enter the word which you want to search :")
8 if w in pair:
9 print(w," found")
10
11 else:
12 print(w," not found")

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

PYTHON LAB Manual CSE AIML ,JBIET. Page 21


3.Take a string as (“1234567890”) and create a pair
{(1,2),(3,4),(5,6),(7,8),(9,0)} using tuple.

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

8 var1 = {"A": 2,"B": 4,"C": 6 }


9 print("the content of dictionary variable var1 :",var1);
10 print("the key of var1 : ",var1.keys());
11 print("the items are :",var1.items());

PYTHON LAB Manual CSE AIML ,JBIET. Page 22


12 print("the value of A is : ",var1.get("A"));
13
14 #print("'A' is present or not ",var1.has_key("A"));
15 var2 = {"D": 8 }
16 var1.update(var2)
17 print ("Value : ",var1);
18 print("values of var1 are : ",var1.values());
19

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

PYTHON LAB Manual CSE AIML ,JBIET. Page 23


if "elephant" in animals:
print("elephant is present.")
else:
print("No elephant")

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)

s1 = Student(input("Enter Name :"),input("Enter Roll No :"))


s2 =Student(input("Enter Name :"),input("Enter Roll No :"))
s1.showStudent()

PYTHON LAB Manual CSE AIML ,JBIET. Page 24


s2.showStudent()

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

PYTHON LAB Manual CSE AIML ,JBIET. Page 25


c1=Customer(input("Enter The Customer Name :"),int(input("Enter The
Ammount :")));
c1.show();
c1.withdraw(int(input("How much amount u want to withdraw : ")));
c1.show();
c1.deposit(int(input("How much amount u want to deposit : ")));
c1.show();

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

print("Great, you successfully entered an integer!")

output:

PYTHON LAB Manual CSE AIML ,JBIET. Page 26


C:\python>python ex8.1.py
Please enter an integer: 8
Great, you successfully entered an integer!

C:\python>python ex8.1.py
Please enter an integer: a
No valid integer! Please try again ...
Please enter an integer:

2. Handel the exceptions that are come at the time of division.

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:

PYTHON LAB Manual CSE AIML ,JBIET. Page 27


13. print("Result: ",div);
14. break
15. finally:
16. print("finally exception handeled..")
17.

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

Write a python script to perform inheritance.


a) Write a python script to find area of triangle.

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

PYTHON LAB Manual CSE AIML ,JBIET. Page 28


for i in range(self.n):
print("Side",i+1,"is",self.sides[i])

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

2. Python script to write the contents into a File file.txt


file = open("file.txt", "w")
file.write("Python is a great language.\nYeah its great!!\n")
# Close opend file
file.close()

3. Python script to read the contents from a File file.txt


4. # Open a file
5. file = open("file.txt", "r+")
6. str = file.read(10);
7. print ("Read String is :", str)
8. # Close opend file
9. file.close()
10.

4. Python script to seek the file positions from a File foo.txt


#Open a file
file= open("file.txt", "r+")
str = file.read(13);
print ("Read String is : ", str)

# Check current position


position = file.tell();

PYTHON LAB Manual CSE AIML ,JBIET. Page 30


print ("Current file position : ", position)

# Reposition pointer at the beginning once again


position = file.seek(0, 0);
str = file.read(10);
print ("Again read String is : ", str)
# 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....")

# prepare a cursor object using cursor() method


cursor = conn.cursor()

# execute SQL query using execute() method.


cursor.execute("SELECT VERSION()")

# Fetch a single row using fetchone() method.


data = cursor.fetchone()

print ("Database version : %s " % data)

# disconnect from server


conn.close()

PYTHON LAB Manual CSE AIML ,JBIET. Page 31


output:
C:\python>python mysqldb.py
connection established....
Database version : 8.0.37

2. Create Database table EMPLOYEE:

import MySQLdb

# Open database connection


db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )

# prepare a cursor object using cursor() method


cursor = db.cursor()

# Drop table if it already exist using execute() method.


cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")

# Create table as per requirement


sql = """CREATE TABLE EMPLOYEE (
FIRST_NAME CHAR(20) NOT NULL,
LAST_NAME CHAR(20),
AGE INT,
SEX CHAR(1),
INCOME FLOAT )"""

cursor.execute(sql)

# disconnect from server


db.close()

3. SQL INSERT statement to create a record into EMPLOYEE table

import MySQLdb

# Open database connection


db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )

# prepare a cursor object using cursor() method


cursor = db.cursor()

PYTHON LAB Manual CSE AIML ,JBIET. Page 32


# Prepare SQL query to INSERT a record into the database.
sql = """INSERT INTO EMPLOYEE(FIRST_NAME,
LAST_NAME, AGE, SEX, INCOME)
VALUES ('Mac', 'Mohan', 20, 'M', 2000)"""
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()

# disconnect from server


db.close()

Above example can be written as follows to create SQL queries dynamically –

import MySQLdb

# Open database connection


db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )

# prepare a cursor object using cursor() method


cursor = db.cursor()

# Prepare SQL query to INSERT a record into the database.


sql = "INSERT INTO EMPLOYEE(FIRST_NAME, \
LAST_NAME, AGE, SEX, INCOME) \
VALUES ('%s', '%s', '%d', '%c', '%d' )" % \
('Mac', 'Mohan', 20, 'M', 2000)
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()

# disconnect from server


db.close()

PYTHON LAB Manual CSE AIML ,JBIET. Page 33


EXPERIMENT 12
1. The following procedure queries all the records from EMPLOYEE table having salary more
than 1000

import MySQLdb

# Open database connection


db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )

# prepare a cursor object using cursor() method


cursor = db.cursor()

# Prepare SQL query to INSERT a record into the database.


sql = "SELECT * FROM EMPLOYEE \
WHERE INCOME > '%d'" % (1000)
try:
# Execute the SQL command
cursor.execute(sql)
# Fetch all the rows in a list of lists.
results = cursor.fetchall()
for row in results:
fname = row[0]
lname = row[1]
age = row[2]
sex = row[3]
income = row[4]
# Now print fetched result
print "fname=%s,lname=%s,age=%d,sex=%s,income=%d" % \
(fname, lname, age, sex, income )
except:
print "Error: unable to fecth data"
# disconnect from server
db.close()

Update Operation
2. The following procedure updates all the records having SEX as 'M'. Here, we increase AGE of

PYTHON LAB Manual CSE AIML ,JBIET. Page 34


all the males by one year.

import MySQLdb

# Open database connection


db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )

# prepare a cursor object using cursor() method


cursor = db.cursor()

# Prepare SQL query to UPDATE required records


sql = "UPDATE EMPLOYEE SET AGE = AGE + 1
WHERE SEX = '%c'" % ('M')
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()

# disconnect from server


db.close()

3. Following is the procedure to delete all the records from EMPLOYEE where AGE is more than
20

import MySQLdb

# Open database connection


db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )

# prepare a cursor object using cursor() method


cursor = db.cursor()

# Prepare SQL query to DELETE required records


sql = "DELETE FROM EMPLOYEE WHERE AGE > '%d'" % (20)
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()

# disconnect from server


db.close()

PYTHON LAB Manual CSE AIML ,JBIET. Page 35


7.Viva Questions

Experiment-1

1. How to take user input data in python.


2. What is difference between sring and character in python.
3. What is arithmetic operations in python.
4. Do we use typecasting in python.
5. What is difference between / and % operation.

Experiment-2

1. What is quardratic equation.


2. What is roots of quardratic equation.
3. What is difference between operand and operator.
4. What is difference between relational and logical operator.
5. What is operator precedence.

Experiment-3

1. What is function in python.


2. What is recursive function.
3. What is non-recursive function.
4. What is difference between input() and raw input()
5. How to give comment in python.

Experiment-4

1. What is string in python.

PYTHON LAB Manual CSE AIML ,JBIET. Page 36


2. What are various string functions in python.
3. What are various string methods in python.

Experiment-5

1. What is List in python.


2. How to Join two Lists in python.
3. How to slice Lists inpython.
4. What are various List functions in python.
5. What is palindrome.

Experiment-6

1. What is tuple in python.


2. What is difference between list and tuple in python.
3. What are list functions like append, sort, reverse in python.

Experiment-7

1. What is tuple() in python.


2. How to use cmp() in python.
3. What are tuple functions like len(), max() and min() in python.

Experiment-8

1. What is dictionary in python.


2. What is concept of Key in dictionary in python.
3. What are various dictionary functions in python.

Experiment-9

1. What is class in python.


2. How to create object in python.
3. What is sytax of class in python.

Experiment-10

1. What is exception in python.

PYTHON LAB Manual CSE AIML ,JBIET. Page 37


2. How to handle exception in python.
3. What is sytax of exception handling in python.

Experiment-11

1. What is inheritance in python.


2. What do you mean by inheritance and multiple inheritance.
3. What is sytax of inheritance in python.

Experiment-12

1. What are various file handling operations in python.


2. What are various DBMS operations in python.
3. How to use DBMS in python.

PYTHON LAB Manual CSE AIML ,JBIET. Page 38

You might also like