You are on page 1of 31

H.M. SR. SEC.

SCHOOL

Session: 2020-21
PRACTICAL FILE
ON
PYTHON PROGRAMS & MYSQL

Submitted to: Submitted by:


Mrs.Ruchi Sharma Purshotam
18
Acknowledgement
I would like to express my special
thanks of gratitude to my teacher
Mrs.Ruchi Sharma as well as our
principal Mrs. Neena Singh who
gave me the golden opportunity to
do this wonderful practical based
on ‘Python & MySql’, which also
helped me in doing a lot of
research and i came to know about
so many things I am really thankful
to them.
Secondly i would also like to thank
my parents and friends who helped
me a lot in finalizing this practical
file within the limited time frame.
Certificate
This is to certify that “Purshotam”
of class XII from H.M. Sr. Sec.
School has completed his practical
file under my supervision. He has
taken proper case and shown
utmost sincerity in completion of
this practical file. I certify that this
file is up to my expectation and as
per guidance issued by C.B.S.E.
Signature of Signature of
Examiner Subject Teacher
_____________ ___________
Signature of
Principal
_________________
INDEX
P1. WAP to input a year and check whether the year is leap year or not. REMARKS

P2. WAP to input 3 numbers and print the greatest number using nested if.
P3. WAP to take inputs for the name of person and age. Check whether a person
is eligible to Vote or not.
P4. WAP to take inputs for two numbers and an operator (+, -, /, *). Based on
the operator calculate and print the result.
P5. WAP to print Fibonacci series up to n terms.

P6. WAP to print the patterns.


P7. WAP that reads a line and prints its statistics like no. of uppercase &
lowercase letters/ no. of alphabets & digits.

P8. WAP to find an elements index or position for index in a particular element.

P9. Write a function Div3and5() that takes numeric elements of tuple and
returns the sum of elements and check whether sum is divisible by 3 and 5 or
not.
P10. Create a module lengthconversion.py that stores functions for various
length conversions like km to mile, mile to km, feet to inches & inches to feet.

P11. Write a program to read a file “poem.txt” and print the contents of file
along with number of vowels present in it.

P12.WAP to read a file "poem.text" and count the no. of words which are "to" and
"the" in the poem text file.
P13. WAP to read a file and display words less than 4 length as well as count uppercase
alphabets.

P14. WAP to create a binary file and modify its content.


P15. WAP to create a CSV file and perform reading and writing operations on
it.
P16. WAP to implement stack and its operations like push, pop, display.
P17. WAP to establish connection with MySQL and create a database class 12th &
display in MySQL.

P18. WAP to establish connection with MySQL and perform Insert Operation.

P19. WAP to establish connection with MySQL and perform Update Operation.
P20. Create a student table and insert data. Implement the following SQL
commands on the student table like show, use, desc, update, order by,
group by, delete and aggregate functions.
Practical -1
Objective: - WAP to input a year and check whether the year is leap year or not
y=int(input("Enter the year: "))
if y%400==0:
print("The year is a Century Leap Year")
elif y%100!=0 and y%4==0:
print("Year is a Leap year")

else:
print("Year is not a leap year")
Enter the year: 2000
The year is a Century Leap Year

Output: -
Practical -2

Objective: - WAP to input 3 numbers and print the greatest number using nested if.
a=float(input("Enter the first number:-"))
b=float(input("Enter the second number:-))
c=float(input("Enter the third number:-"))
if a>=b:
if a>=b:
print("First number",a,"is greatest")
if b>a:
if b>c:
print("Second number",b,"is greatest")
if c>a:
if c>b:
print("Third number",c,"is greatest")
Enter the first number:-4
Enter the second number:-2
Enter the third number:-2.1
First number 4 is greatest

Output: -
Practical -3

Objective: - WAP to take inputs for name of person and age. Check whether a person is
eligible to Vote or not.

name=input("Enter name ")


age=int(input("Enter age "))
if(age>=18):
print("you can vote")
else:
print("you cannot vote")

Output:-
Practical -4

Objective: - WAP to take inputs for two numbers and an operator (+, -, /, *). Based on the
operator calculate and print the result.

a=int(input("Enter 1st no "))


b=int(input("Enter 2nd no "))
op=input("Enter the operator (+,-,,/) ")
if(op=="+"):
c=a+b
print("Sum = ",c)
elif(op==""):
c=a*b
print("Product = ",c)
elif(op=="-"):
if(a>b):
c=a-b
else:
c=b-a
print("Difference = ",c)
elif(op=="/"):
c=a/b
print("Division = ",c)
else:
print("Invalid operator")
Practical -5
Objective: - WAP to print Fibonacci series up to n terms.

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


first = 0
second = 1
if n <= 0:
print("Incorrect input")
elif n == 1:
print(second)
else:
for i in range(n):
print(first,end=' ')
temp = first
first = second
second = first+temp

Output: -
Practical -6
Objective: - WAP to print the patterns.

Row=int(input("Enter the number of rows:"))


for i in range(1,Row+1):
for j in range(1,i+1):
print(j,end=" ")
print()

Row=int(input("Enter the number of rows:"))


for i in range(1,Row+1):
for j in range(1,i+1):
print('*',end=" ")
print()

Output:-
Practical -7
Objective: - WAP that reads a line and prints its statistics like no. of uppercase &
lowercase letters/ no. of alphabets & digits.

line=input("Enter a line:")
lowercount= uppercount=0
digitcount = alphacount=0
for a in line:
if a.islower():
lowercount += 1
elif a.isupper():
uppercount += 1
elif a.isdigit():
digitcount += 1
if a.isalpha():
alphacount += 1
print("Number of uppercase letters :", uppercount)
print("Number of lowercase letters :", lowercount)
print("Number of alphabets :", alphacount)
print("Number of digits :", digitcount)

Output: -
Practical -8
Objective: - WAP to find an elements index or position for index in a particular
element.

Elements=input("Enter the element of tuple:")


Tuple=tuple(Elements)
Char=input("Enter a single line character without quotes:")
if Char in Tuple:
Count=0
for a in Tuple:
if a!=Char:
Count+=1
else:
break
print(Char,"is at index",Count,"in",Tuple)
else:
print(Char,"is not in",Tuple)

Output: -
Practical -9
Objective: - Write a function Div3and5() that takes numeric elements of tuple and return
the sum of elements and check whether sum is divisible by 3 and 5 or not.

def div3and5(sum):
if sum%3==0 and sum%5==0:
print("Sum is divisible by 3 & 5")
else:
print("Sum is not divisible by 3 & 5")
a=[]
size=int(input("How Many Elements You Want To Enter:-"))
for i in range(size):
e=int(input("Enter the Element:-"))
a.append(e)
sum=0
for i in range(size):
sum=sum+a[i]
print("Sum of List's Elements:-",sum)
div3and5(sum)

Output: -
Practical -10
Objective: - Create a module lengthconversion.py that stores function for various
length conversion like kmtomile, miletokm, feettoinches & inchestofeet.

#It is a module named lengthconversion.py


def miletokm():
n=int(input("Enter the distance in mile:"))
result=n*1.60
print("Distance in kilometer is:-",result,"km")

def kmtomile():
n=int(input("Enter the distance in kilometer:"))
result=(1/1.60)*n
print("Distance in mile is:-",result,"mile")

def feettoinches():
n=int(input("Enter the length in feet:"))
result=n*12
print("Length in inches is:-",result,"inches")

def inchestofeet():
n=int(input("Enter the length in inches:"))
result=(1/12)*n
print("Length in feet is:-",result,"feet")

#Main Program:-
import lengthconversion as lc
print("Here we are doing kilometer to mile and vice-versa conversion")
lc.miletokm()
lc.kmtomile()
print("Here we are doing feet to inches and vice-versa conversion")
lc.feettoinches()
lc.inchestofeet()
Output: -
Practical -11
Objective: - Write a program to read a file “poem.txt” and print the contents of file along
with number of vowels present in it.

f=open("poem.txt",'r')
st=f.read()
print("Contents of file :")
print(st)
c=0
v=['a','e','i','o','u']
for i in st:
if i.lower() in v:
c=c+1
print("*****FILE END*****")
print()
print("Number of vowels in the file =",c)
f.close()

Output:-
Practical -12
Objective: - WAP to read a file "poem.text" and count the no. of words which are
"to" and "the" in the poem text file.

file=open("Poem.txt","r")
read=file.read()
word=read.split()
print("content of the poem is-")
print(word)
a=0
for i in word:
if i=="to" or i=="the" or i=="The" or i=="To":
a=a+1
print('total words "the" and "to" is-',a)
file.close()

Output: -
Practical -13
Objective: - WAP to read a file and display words less than 4 length as well as
count uppercase alphabets.

file=open("Poem.txt","r")
read=file.read()
word=read.split()
print("content of the poem is-")
print(word)
a=0
for i in word:
if len(i)<4:
a=a+1
print("Number of words less then length 4 is ",a)

s=0
for b in read:
if b.isupper():
s=s+1
print("Number of uppercse alphabets is " ,s)
file.close()

Output: -
Practical -14
Objective: - WAP to create a binary file and modify its content.
import pickle
import os
def createb():
f1=open("abc.dat","wb")
l=["My name is Divya","I am a student"]
pickle.dump(l,f1)
f1.close
def readb():
f1=open("abc.dat","rb")
g=pickle.load(f1)
print(g)
f1.close()
def changeb():
f2=open("abc.dat","rb")
f3=open("temp.dat","wb")
h=pickle.load(f2)
f=[ ]
for t in h:
if t=="I am a student":
f.append("I study in class 12th")
else:
f.append(t)
pickle.dump(f,f3)
f2.close()
f3.close()
os.remove("abc.dat")
os.rename("temp.dat","abc.dat")
createb()
readb()
changeb()
readb()

Output: -
Practical -15
Objective: - WAP to create a CSV file and perform reading and writing operations on it.

import csv
def write():
f=open("Items.csv","w",newline='')
swriter=csv.writer(f)
swriter.writerow(['Ino','Iname','Qty','price'])
rec=[]
while True:
n=int(input("Item No:-"))
name=(input("Item Name:-"))
qty=int(input("No. of Quantity:-"))
p=int(input("Price:-"))
data=[n,name,qty,p]
rec.append(data)
ch=input("More (Y/N)?")
if ch in "n/N":
break

swriter.writerows(rec)
print("Data written in CSV file successfuly")
f.close()

def read():
f=open("Items.csv","r")
print("Reading data from CSV file")
sreader=csv.reader(f)
for i in sreader:
print(i)

write()
read()
Output: -

CSV File: -
Practical -16
Objective: - WAP to implement stack and its operations like push, pop, display.

def isEmpty(stk):
if stk==[]:
return True
else:
return False

def push(stk,item):
stk.append(item)
top=len(stk)-1
def pop(stk):
if isEmpty(stk):
return"Underflow"
else:
item=stk.pop()
if len(stk)==0:
top=None
else:
top=len(stk)-1
return item
def peek(stk):
if isEmpty(stk):
return "Underflow"
else:
top=len(stk)-1
return stk[top]

def display(stk):
if isEmpty(stk):
print("stack empty")
else:
top=len(stk)-1
print(stk[top],"<-top")
for a in range(top-1,-1,-1):
print(stk[a])

stack=[]
top=None
while True:
print("STACK OPERATION")
print("1.Push")
print("2.pop")
print("3.peek")
print("4.Display stack")
print("5.exit")
ch=int(input("Enter your choice(1-5):"))
if ch==1:
item=int(input("Enter item:"))
push(stack,item)
elif ch==2:
item=pop(stack)
if item=="Underflow":
print("Underflow! stack is empty!")
else:
print("Popped itemis",item)
elif ch==3:
item=peek(stack)
if item=="underflow":
print("underflow! stack is empty!")
else:
print("topmost item is ",item)
elif ch==4:
display(stack)
elif ch==5:
break
else:
print("invalid choice!")

Practical -17
Objective: - WAP to establish connection with MySQL and create a database class12th &
display in MySQL.

import mysql.connector
con= mysql.connector.connect(
host="localhost",
user="root",
password="Gaurav@12"
)

cur=con.cursor()
cur.execute("create database class12th")
print("Query created successfully....")

Output: -
Practical -18
Objective: - WAP to establish connection with MySQL and perform Insert Operation.

import mysql.connector

con= mysql.connector.connect(
host="localhost",
user="root",
password="Gaurav@12",
database="class12th"
)

cur=con.cursor()
r=int(input("Enter Roll_No:-"))
sn=(input("Enter Student Name:-"))
a=int(input("Enter Age:-"))
m=int(input("Enter Total Marks:-"))
query="insert into student values({},'{}',{},{})".format(r,sn,a,m)
cur.execute(query)
con.commit()
print("Row inserted successfully....")
cur.execute("select * from student")
for x in cur:
print(x)

Output: -

Practical -19
Objective: - WAP to establish connection with MySQL and perform Update Operation.

import mysql.connector
con= mysql.connector.connect(
host="localhost",
user="root",
password="Gaurav@12",
database="class12th"
)
cur=con.cursor()
query="update student set marks=350 where r_no=5"
cur.execute(query)
con.commit()
print("Row updated successfully....")
cur.execute("select * from student")
for x in cur:
print(x)

Output: -
Earlier Table:

Table After Updating:

Practical - 20
Objective: - Create a student table and insert data. Implement the following
SQL commands on the student table like show, use, desc, update, order by,
group by, delete and aggregate functions.

1.Show and Use: - 2. select command: -


3. Update command: - 4. Order By command: -

5. Order By desc command: - 6. Order By with condition: -

7. Group by Command: -
8. Having Clause: -

9. Sum( ) Function: - 10. AVG( ) Function: -

10. MAX( ) Function: - 11. Count(*) Function:-


CoutCount Function

You might also like