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

vineet

Uploaded by

ashifr458
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)
19 views40 pages

vineet

Uploaded by

ashifr458
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
You are on page 1/ 40

INDEX

S.no Practical’s Teacher’s sign.


1. Python programs (using
python and function).
2. Stack implementation.
3. File handling.
4. SQL.
5. Python Mysql(connectivity).
PYTHON PROGRAMS
Practical implementation 1:-

1.Write a program to swapping two numbers.


num1=int(input(‘enter num1 value:’)
num2=int(input(‘enter num2 value:')
print(‘value of num1 before swapping:’,num1)
print('value of num2 before swapping:’,num2)
num1,num2=num2,num1 print(‘value of
num1 after swapping:’,num1) print('value of
num2 after swapping:’,num2)

Output:-

Practical implementation 2:-

2.Write a program to check a number is prime or not.


num=int(input(‘enter a number to check prime:’))
count=0
if num>1:
for i in range(1,num+1):
if(num%i) ==0:
count=count+1
if count ==2:
print(‘number is prime’)
else:
print('number is not prime’)

6
Practical implementation 3:-

3.Write a program to find the factorial of a number:-


factorial=1
num=int(input(‘enter a num to get factorial:’)
if num<0:
print(‘factorial does not exist for negative number’)
elif num=0:
print(‘factorial of 0 is 1’)
else: for i in range(1,num+1):

factorial=factorial*i
print(‘the factorial of’,num,’is’,factorial)

Pactical implementation 4:-

4.Write a program to print Fibonacci series using functions.

n1=0
n2=1 print(n1) print(n2)
for i in range(2,10):

sum=n1+n2
print(sum)
n1=n2
n2=sum

7
Practical implementation 5:-
5.Write a program to find the sum of all elements of a list.

arr=[1,2,3,4,5]
print(sum(arr))

Practical implementation 6:-


6.Write a program to find largest/smallest number in a list/tuple.

arr=[1,2,3,4,5]
max=arr[0] n=len(arr) for
i in range(1,n):

if arr[i]>max:
max=arr[i]
print(max)

arr=[1,2,3,4,5]
min=arr[0] n=len(arr) for i
in range(1,n):

if arr[i]<min:
min=arr[i]
print(min)

8
Practical implementation 7:-
7. Program to enter two numbers and print the arithmetic operations like +,-,*, /, //
and %.

result = 0
val1 = float(input("Enter the first value :"))
val2 = float(input("Enter the second value :"))
op = input("Enter any one of the operator (+,-,*,/,//,%)")
if op == "+":
result = val1 + val2
elif op == "-":
result = val1 - val2
elif op == "*":
result = val1 * val2
elif op == "/":
if val2 == 0:
print("Please enter a value other than 0")
else:
result = val1 / val2
elif op == "//":
result = val1 // val2
else:
result = val1 % val2
print("The result is :",result)

0utput:-

9
Practicalimplementation8:-
8.Write a Program to enter the string and to check if it’s palindrome or not using
loop.

msg=input("Enter any string : ")


newlist=[]
newlist[:0]=msg
l=len(newlist)
ed=l-1
for i in range(0,l):
if newlist[i]!=newlist[ed]:
print ("Given String is not a palindrome")
break
if i>=ed:
print ("Given String is a palindrome")
break
l=l-1
ed=ed-1

Output:-

10
Practicalimplementation9:-
9.Write a Program to enter the number and print the Floyd’s Triangle in decreasing order.

n=int(input("Enter the number :"))


for i in range(n,0,-1):
for j in range(n,i-1,-1):
print (j,end=' ')
print('\n')

Output:-

Practicalimplementation10:-
10.WAP to convert Celsius into Fahrenheit.

celsius = float(input("Enter temperature in Celsius: "))


fahrenheit = (celsius * 9/5) + 32
print(f"Temperature in Fahrenheit: {fahrenheit}")

Output:-

11
Practicalimplementaion11:-
11.Write a python program to reverse a string.

S=input("enter a string:")
print(S[::-1]
Output:-

Practicalimplementation12:-
12.Write python program to obtain temperature of 7 days and then display the average
temperature of the week.

d1=float(input("enter day 1 temperature:"))


d2=float(input("enter day 2 temperature:"))
d3=float(input("enter day 3 temperature:"))
d4=float(input("enter day 4 temperature:"))
d5=float(input("enter day 5 temperature:"))
d6=float(input("enter day 6 temperature:"))
d7=float(input("enter day 7 temperature:")) avg=
(d1+d2+d3+d4+d5+d6+d7)/7 print("Average
temperature of seven days:",avg)

OUTPUT:-

12
Practicalimplementation13:-
13.Write a program to create a user defined function to display a line like ‘--------’(20
dashes).

def display():
for i in range(20):
print("-",end='')
display()

OUTPUT:-

Practicalimplementation14:-
14.Write a program to create a user defined function ‘area’ to calculate and display area of
rectangle.

def area():
l=int(input("enter length:"))
b=int(input("enter breadth:"))
a=l*b
print("area=",a)
area()

OUTPUT:-

13
Practicalimplementation15:-
15. Write a function power to find x to the power y.if y is not inputted square of x should be
calculated.

def power(x,y=2):
r=1
for i in range(y):
r=r*x
print("power=",r)
base=int(input("enter a number:"))
expo=int(input("enter a number:"))
print("calling function with default parameter")
power(base)
print("calling function with all parameters")
power(base,expo)

OUTPUT:-

14
STACK
Practicalimplementation1:-
1. Write a program to implement a stack using list(PUSH,POP,PEEK & DISPLAY Operation on

Stack).
def PUSH():
if Stack==[]:
print("Stack is empty")
else:
print(Stack[-1])
def Display():
if Stack==[]:
print("Stack is empty")
else:
for i in range(len(Stack)-1,-1,-1):
print(Stack[i])
Stack=[]
while True:
Inputch=int(input("enter/n1 for PUSH\n2 for POP\n3 for PEEK\n4 fo Display"))
if Inputch==1:
PUSH()
elif Inputch==2:
POP()
elif Inputch==3:
PEEK()
elif Inputch==4:
Display()
else:
break

Output:-

15
Practicalimplementation2:-
2. Write a program to using function PUSH(Arr),where Arr is a list of numbers.From this list
push all numbers divisible by 5 into a stack implemented by using a list.Display the stack if it
has atleast one element,otherwise display appropriate error message.

def PUSH(Arr):
for i in Arr:
if i%5==0:
Stack.append(i)
def Display():
print("Display Stack")
if Stack==[]:
print("No value is divisible by 5 so Stack is empty")
else:
for i range(len(Stack)-1,-1,-1):
print(Stack[i])
Stack=[]
Arr=[11,22,45,67,89,43,223,67,90,89,25,50]
while True:
Inputch=int(input("enter \n1 for PUSH\n2 for Display"))
if Inputch==1:
PUSH(Arr)
elif Inputch==2:
Display()
else:
print("exit")
break

OUTPUT:-

16
Practicalimplementation3:-
3. Write a program using function POP(Arr),where Arr is a Stack implemented by a list of
Numbers .The function returns the value deleted from Stack.

def PUSH():
value=int(input("enter value for Stack:"))
Stack.append(value)
def POP(Stack):
if Stack==[]:
return "Stack is empty so, underflow"
else:
return Stack.pop()
def Display():
print("Display Stack")
if Stack==[]:
print("Stack is empty")
else:
for i in range(len(Stack)-1,-1,-1):
print(Stack[i])
Stack=[]
while True:
Inputch=int(input("enter\n1 for PUSH\n2 for POP\n3 for Display"))
if Inputch==1:
PUSH()
elif Inputch==2:
Del=POP(Stack)
print("The value is deleted",Del)
elif Inputch==3:
Display()
else:
print("exit")
break

17
OUTPUT:-

18
FILE HANDLING
Practicalimplementation1:-
1. Write a program to read a text file line by line and display each words separated by #.

def wordsep():
f=open("Quotes.txt","r")
lines=f.readlines()
for line in lines:
words=line.split()
for word in words:
print(word+"#",end="")
print()
wordsep()

def wordsepr():
f=open("Quotes.txt","r")
while True:
line=f.readline()
if line=='':
break
else:
words=line.split()
for i in words:
print(i+'#',end='')
print()
wordsepr()

19
Practicalimplementation2:-
2.Write a python program to read a text file and find the number of
vowels/consonants/uppercase/lowercase characters in the file.

def Countvcul():
f=open("Report.txt","r")
V=C=U=L=0
data=f.read()
for i in data:
if i.isalpha():
if i.isupper():
U+=1
if i.islower():
L+=1
if i.lower() in 'aeiou':
V+=1
else:
C+=1
print("Vowels=",V)
print("Consonants=",C)
print("Uppercase=",U)
print("Lowercase=",L)
Countvcul()

20
Practicalimplementation3:-
3.Write a python program to remove all the lines that contain the character ‘a’ in a file and
write it to another file.

def Remove():
f=open("SampleOld.txt","r")
lines=f.readlines()
fo=open("SampleOld.txt","w")
fn=open("SampleNew.txt","w")
for line in lines:
if 'a' in line:
fn.write(line)
else:
fo.write(line)
print("Data updated in Sample Old File..and created samplenew file also..")
Remove()

OUTPUT:-

21
Practicalimplementation4:-
3. Write a python program to create a binary file with name and roll number and display
the record.

import pickle
def write():
f=open("students.dat","wb")
while True:
r=int(input("enter Roll no. :"))
n=input("enter Name:")
Data=[r,n]
pickle.dumb(Data,f)
ch=input("hey user do you want to input more? (Y/N)")
if ch in 'Nn':
break
f.close()
def Read():
f=open("students.dat","rb")
try:
while True:
rec=pickle.load(f)
print(rec)
except EOFError:
f.close()
write()
Read()

OUTPUT:-

22
Practicalimplementation5:-
5.Write a python program to create a binary file with name and roll number. Search for a
Given roll number and display the name,if not found display appropriate message.

import pickle
def write():
D={}
f=open("students.dat","wb")
while True:
r=int(input("enter Roll no. :"))
n=input("enter Name:")
D['Roll No']=r
D['Name']=n
pickle.dump(D,f)
ch=input("hey user do you want to input more? (Y/N)")
if ch in 'Nn':
break
f.close()
def Search():
found=0
rollno=int(input("enter roll no whose name you want to display:"))
f=open("students.dat","rb")
try:
while True:
rec=pickle.load(f)
if rec['Roll No']==rollno:
print(rec['Name'])
found=1
break
except EOFError:
f.close()
if found==0:
print("sorry....No record found...")
write()
Search()

OUTPUT:-

23
Practical implementation 6:-
6.Write a python program to create a binary file with rollno,name and marks.Input a rollno
and update marks.

import pickle
f=open('student.dat','wb')
rec=[]
while True:
rn=int(input("enter roll no.:"))
name=input("enter name:")
marks=int(input("enter marks:"))
l=[rn,name,marks]
rec.append(l)
ch=input("want to enter more?")
if ch in 'Nn':
break
pickle.dump(rec,f)
print("The student details are",rec)
f.close()
f=open("student.dat","rb")
found=0
try:
while True:
rec=pickle.load(f)
srn=int(input("enter the roll no. whose marks you want to update:"))
for i in rec:
if i[0]==srn:
smks=int(input("enter the new marks:"))
i[2]=smks
print("The updated record of the student is:",i)
found=1
break
except:
f.close()
if found==0:
print("no such record found....")
24
OUTPUT:-

25
Practicalimplementation7:-
7.Create a csv file by entering u-id and password,read and search the password for given
user-id.

import csv
def write():
f=open("user.csv",'w',newline='')
w1=csv.writer(f)
w1.writerow(["UID","Password"])
while True:
uid=input("enter user-id:")
pswrd=input("enter password:")
l=[uid,pswrd]
w1.writerow(l)
ch=input("want to enter more?")
if ch in 'Nn':
break
f.close()
def read():
f=open("user.csv",'r',newline='')
r1=csv.reader(f)
for i in r1:
print(i)
f.close()
def search():
found=0
f=open("user.csv",'r',newline='')
r1=csv.reader(f)
uidd=input("enter the user-id whose password you want to search:")
for i in r1:
if i[0]==uidd:
print("it's password is:",i[1])
found=1
if found==0:
print("no such record found")
f.close()
write()
read()
search()

26
OUTPUT:-

27
DATABASE MANAGEMENT
Practicalimplementation1:-
1. Write a command to create a Database.

mysql>create database Practical;

Practicalimplementation2:-
2. Write a command to use created database.

mysql>use database Practical;

Practicalimplementation3:-
3.Write a command to create a table student including
(Rno,AdmissionNo,Name,Age,Gender and Marks).

mysql>create table student


(Rno int primary key,
AdmissionNo varchar(10) unique,
Name varchar(10),
Age int check (age between 14 and 19)
Gender varchar(10),
Marks int(10));

Output:-

28
Practicalimplementation4:-
4. Write a command to insert data in a given table(student).

mysql> insert into student values


-> (1,'s101','kanhaiya',17,'M',98),
-> (2,'s102','ved',17,'M',96),
-> (3,'s103','sarthak',18,'M',95),
-> (4,'s104','shivam',18,'M',90),
-> (5,'s105','pari',16,'M',95);

Output:-

Practicalimplementation5:-
5. Write command to display the data of table.

mysql> select * from student;

Output:-

29
Practicalimplementation6:-
6. Write a command to Alter table to add new attributes.

mysql> alter table student add city varchar(20);

Output:-

Practicalimplementation7:-
7. Write a command to modify data type of a column in a table.

mysql> alter table student modify city char(20);

Before:-

After:-

30
Practicalimplementation8:-
8. Write a command to alter table to drop attribute.

mysql> alter table student drop city;

Output:-

Practicalimplementation9:-
9. Write a command to update table to modify data.

mysql> update student set marks=98 where Rno=2;

Output:-

31
Practicalimplementation10:-
10.Write a command to display data in ascending/descending order.

Ascending:-
Select * from student order by Name;
OR
Select * from student order by Name asc;

Output:-

Descending:- select * from student order by Name desc;

Output:-

32
Practicalimplementation11:-
11.Write a command to delete to remove tuple(s).

mysql> delete from student where Rno=5;

Output:-

Practicalimplementation12:-
12.Write a command to find min/max.

mysql> select min(marks),max(marks) from student;

Output:-

33
Practicalimplementation13:-
13.Write a command to find average and sum.

mysql> select avg(marks),sum(marks) from student;

Output:-

Practicalimplementation14:-
14.Write a command to find count.

mysql> select count(*),count(Name) from student;

Output:-

Practicalimplementation15:-
15.Write a command to use group by.

mysql> select gender,count(*) from student group by gender;

Output:-

34
JOINS
Practicalimplementation16:-
16.Write a command to create a 2nd table with reference to any existing table.

Table-1:- student (existing table).

Table-2:- Books (2nd table).

35
Practicalimplementation17:-
17.Inserting data in 2nd table Books.

mysql> insert into Books values


-> (1,'mathematics'),
-> (2,'biology'),
-> (3,'english'),
-> (4,'chemistry'),
-> (5,'english');
mysql> select*from Books;

Output:-

Practicalimplementation18:-
18.Write a command to display Cartesian product of two tables.

mysql> select * from student,Books;

Output:-

36
Practicalimplementation19:-
19.Write a command to create equi join of two tables.

mysql> select * from student,Books where student.Rno=Books.Rno;

Output:-

Practicalimplementation20:-
20.Write a command to get normal join of two tables.

mysql>select * from student natural join Books where student.Rno=Books.Rno;

Output:-

37
PYTHON MYSQL CONNECTIVITY
Practicalimplementation1:-
1. Write a command to connect SQL with PYTHON.

import mysql.connector
con=mysql.connector.connect(host='localhost',
user='root',
passwd='Kanhaiya01',
database='Practical',
charset='utf8')
if con.is_connected():
print('connected..')
else:
print('not connected...')

Output:-

Practicalimplementation2:-
2. Write a command to insert data in a table in sql through python.

cur=con.cursor()
cur.execute("insert into students values(101,'Kanhaiya',99.99,'delhi')")
con.commit()

Output:-
Step1:-

Step2:-

38
Step3:-

Step4:-

Step5:-

Step6:-

39
Practicalimplementation3:-
3. Write a program to insert data and display the records.

import mysql.connector
con=mysql.connector.connect(host='localhost',
user='root',
passwd='Kanhaiya01',
database='Practical',
charset='utf8')
cur=con.cursor()
while True:
RollNo=int(input('enter RollNO:'))
Name=input('enter Name:')
Marks=float(input('enter Marks:'))
City=input('enter city:')
cur.execute("insert into students values"
"({},'{}',{},'{}')".format(RollNo,Name,Marks,City))
ch=input("hey user do you want to enter new record if yes press Y or y:")
if ch not in "Yy":
break
con.commit()
cur.execute("select*from students")
data=cur.fetchall()
for i in data:
print(i)

Output:-

40
Data stored in sql as shown below:-

Practicalimplementation4:-
4.Write a program to search a specific record,if not found display a message.

import mysql.connector
con=mysql.connector.connect(host='localhost',
user='root',
passwd='Kanhaiya01',
database='Practical',
charset='utf8')
cur=con.cursor()
while True:
Name=input("enter the Name which u want to search:")
cur.execute("select*from students where Name='{}'".format(Name))
data=cur.fetchall()
flag=0
for i in data:
flag=1
print(i)
if flag==0:
print('not found')
ch=input("hey user do u want to find more records,if yes press Y or y:")
if ch not in "Yy":
break

41
Output:-

Practicalimplementation5:-
5.Write a program to update a specific record,if not found display a appropriate message.

import mysql.connector
con=mysql.connector.connect(host='localhost',
user='root',
passwd='Kanhaiya01',
database='Practical',
charset='utf8' )
while True:
cur=con.cursor()
City=input("enter city:")
Name=input("enter Name:")
cur.execute("update students set CIty='{}' where Name='{}'".format(City,Name))
if cur.rowcount!=0:
cur.execute("select*from students")
data=cur.fetchall()
for i in data:
print(i)
else:
print("not found")
ch=input('hey user do u want to update more records,if yes press Y or y')
if ch not in 'Yy':
break

Output:-

42
Practicalimplementation6:-
6. Write a program to delete a specific record.

import mysql.connector
con=mysql.connector.connect(host='localhost',
user='root',
passwd='Kanhaiya01',
database='Practical',
charset='utf8')
cur=con.cursor()
while True:
Name=input('enter Name which u want to delete')
cur.execute("delete from students where Name='{}'".format(Name))
con.commit()
if cur.rowcount==0:
print('not found')
else:
print('done')
ch=input("hey user do u want to delete more records,if yes press Y or y")
if ch not in 'Yy':
Break

Output:-

43
THANK
YOU

44

You might also like