Cs Practical File Vibhu
Cs Practical File Vibhu
SCHOOL,
GAJRAULA
1
INDEX
S.NO. TOPIC PAGE NO.
1. PYTHON FUNCTION 3-15
4. DATABASES 35-46
2
PYTHON FUNCTIONS
def Armstrong(x):
s=0
a=x
while x>0:
k=x%10
s=(s+k)**3
x=x//10
if s==a:
print(“The number is Armstrong”)
else:
print(“The number is not Armstrong”)
def Palindrome(s):
y=""
for i in range(len(s)-1,-1,-1):
y=y+s[i]
if (y==s):
print(“The string is palindrome”)
else:
print(“The string is not a palindrome”)
3
3- Write a function to count the number of vowels and
consonants in a string.
def string(s):
v=c=0
for i in s:
if i.isalpha():
if i in "AaEeIiOoUu":
v=v+1
else:
c=c+1
print(“number of vowels”,v)
print(“number of consonants”,c)
def Lsearch(L,val):
if val in L:
print(“found”)
else:
print(“Not found”)
def Sreverse(str):
y=""
for i in range(len(str)-1,-1,-1):
y=y+str[i]
return(y)
4
6-Write a function to print the sum of digits in a
passed number.
def sumdigit(n):
s=0
while n>0:
k=n%10
s=s+k
n=n//10
return(s)
def revlist(L):
L.reverse()
return(L)
def xyz(L):
for i in range(0,len(L)):
if L[i]%2==0:
L[i]*=3
else:
L[i]*=5
print(L)
5
9-Write a function to pass two parameters x and n as
integers. Calculate the following sum of series and
return the value:-
2 3 n
1+ x/2! + x /4! + x /6! +………x /2n!
def sumofseries(x,n):
s=0
for i in range(0,n+1):
F=1
for j in range (1,2*i+1):
F=F*j
s=s+(x**i)/F
print("Sum of series=",s)
def power(x,n):
y=x**n
return(y)
def location(L):
for i in range(0,len(L)-1):
if i%2==0:
L[i],L[i+1]=L[i+1],L[i]
print(L)
6
12- Write a function to search an element in a list. If
found replace it by 0 and move all the 0 to the
beginning of the list.
def func(L,n):
k=0
for i in range(len(L)):
if L[i]==n:
L[i]=0
for j in range(i,k,-1):
L[j],L[j-1]=L[j-1],L[j]
k=k+1
print(L)
def fibonacci(n):
n1,n2=0,1
print(n1,n2,end=" ")
for i in range(2,n):
n3=n1+n2
n1=n2
n2=n3
print(n3,end=" ")
def SI(P,R,T):
S=(P*R*T)/100
return(S)
7
15- Write a function to accept a 2d list. Display the
sum of even elements of the 2d list.
def xyz():
l=[]
for i in range(r):
row=[]
for j in range(c):
x=int(input("Enter a no."))
row.append(x)
l.append(row)
s=0
for i in range(r):
for j in range(c):
if l[i][j]%2==0:
s+=l[i][j]
print(“Sum of even elements”,s)
8
17- Write a function to check whether the number is
prime or not.
def prime(n):
k=0
for i in range(2,n):
if n%i==0:
k=1
if k==0:
print("It is a prime number")
else:
print("It is not a prime number")
9
CALLING STATEMENTS wITH THEIR
OUTPUTS
1-ARMSTRONG NUMBER
x=int(input("Enter a number"))
Armstrong(x)
OUTPUT
Enter a number 153
The number is Armstrong
2-PALINDROME SERIES
s=input("Enter a string")
Palindrome(s)
OUTPUT
Enter a string madam
The string is palindrome
7- REVERSED LIST
L=eval(input("Enter a list"))
print(revlist(L))
OUTPUT
Enter a list [1,2,3,4,5]
[5, 4, 3, 2, 1]
11
9-SUM OF SERIES:-
1+ x/2! + x2/4! + x3/6! +………xn/2n!
x=int(input("Enter a number="))
n=int(input("Enter a number="))
sumofseries(x,n)
OUTPUT
Enter a number= 5
Enter a number= 5
Sum of series= 4.731639936067019
15
FILE HANDLING
TEXT FILES FUCTIONS
NOTES.TXT FILE CONTENTS
Data Files-
Data files are the files that store data pertaining to a specific application for later
use. The data files can be stored in two ways-
1- Text files - A text file stores information in the form of a stream of ASCII or
Unicode characters. In this each line is terminated of text with a special
character known as EOL (End of line).
2- Binary files – A binary file stores the information in the form of a stream of
bytes. A binary files contains information in the same format in which
information is held in memory. There is no delimiter for a line.
17
def characters():
xf=open("notes.txt","r")
y=' '
l=[]
c=0
while y:
y=xf.readline()
l=y.split()
for i in l:
if len(i)==3 or len(i)==5:
c=c+1
print("Required characters =",c)
xf.close()
19
BINARY FILES
import pickle
import os
def add():
xf=open('stationary.txt',"ab")
IT={}
wish='Y'
while wish=='Y':
itno=int(input("Enter item number "))
desc=input("Enter item name ")
qty=int(input("Enter item quantity "))
rate=float(input("Enter rate "))
IT['INO.']=itno
IT['Description']=desc
IT['Quantity']=qty
IT['Rate']=rate
IT['Amt']=qty*rate
pickle.dump(IT,xf)
wish=input("Add more Y/N ")
xf.close()
import pickle
def modify():
20
Found=False
xf=open('stationary.txt',"rb+")
IT={}
try:
N=int(input("Enter the item number to be modified "))
while True:
rec=xf.tell()
IT=pickle.load(xf)
if IT['INO.']==N:
rate=float(input("Enter new rate "))
IT['Rate']=rate
IT['Amt']=rate*IT['Quantity']
print(IT)
break
xf.seek(rec)
pickle.dump(IT,xf)
Found=True
except EOFError:
if Found==False:
print("No such record")
xf.close()
import pickle
def search():
xf=open('stationary.txt',"rb")
Found=False
IT={}
N=int(input("Enter the item number "))
try:
while True:
IT=pickle.load(xf)
if IT['INO.']==N:
print(IT)
Found=True
except EOFError:
21
if Found==False:
print("No such record")
xf.close()
import pickle
def delete():
yf=open('temp.dat',"wb")
xf=open('stationary.txt',"rb")
Found=False
IT={}
N=int(input("Enter the item number "))
try:
while True:
IT=pickle.load(xf)
if IT['INO.']!=N:
pickle.dump(IT,xf)
else:
Found=True
except EOFError:
if Found==False:
print("Not found")
xf.close()
yf.close()
os.remove("stationary.txt")
os.rename("temp.txt","stationary.txt")
import pickle
def display():
xf=open('stationary.txt',"rb")
IT={}
try:
while True:
IT=pickle.load(xf)
print(IT)
except EOFError:
xf.close()
22
while True:
print("\t\t\t\t XYZ stationary")
print("\t 1. Adding records")
print("\t 2. Modification of records")
print("\t 3. Searching particular details")
print("\t 4. Deleting record")
print("\t 5. Report")
print("\t 6. End of program")
ch=int(input("Enter your choice : "))
if ch==1:
add()
elif ch==2:
modify()
elif ch==3:
search()
elif ch==4:
delete()
elif ch==5:
display()
elif ch==6:
print("END OF PROGRAM")
break
else:
print("Wrong choice enter again")
OUTPUT
XYZ stationary
1. Adding records
2. Modification of records
3. Searching particular details
4. Deleting record
5. Report
23
6. End of program
Enter your choice : 1
Enter item number 1
Enter item name Pen
Enter item quantity 5
Enter rate 100
Add more Y/N Y
Enter item number 2
Enter item name Pencil
Enter item quantity 10
Enter rate 100
Add more Y/N Y
Enter item number 3
Enter item name Copy
Enter item quantity 2
Enter rate 200
Add more Y/N N
XYZ stationary
1. Adding records
2. Modification of records
3. Searching particular details
4. Deleting record
5. Report
6. End of program
Enter your choice : 2
Enter the item number to be modified 3
Enter new rate 100
{'INO.': 3, 'Description': 'Copy', 'Quantity': 2, 'Rate': 100.0, 'Amt': 200.0}
XYZ stationary
1. Adding records
2. Modification of records
3. Searching particular details
4. Deleting record
5. Report
24
6. End of program
Enter your choice : 3
Enter the item number 1
{'INO.': 1, 'Description': 'Pen', 'Quantity': 5, 'Rate': 100.0, 'Amt': 500.0}
XYZ stationary
1. Adding records
2. Modification of records
3. Searching particular details
4. Deleting record
5. Report
6. End of program
Enter your choice : 5
{'INO.': 1, 'Description': 'Pen', 'Quantity': 5, 'Rate': 100.0, 'Amt': 500.0}
{'INO.': 2, 'Description': 'Pencil', 'Quantity': 10, 'Rate': 100.0, 'Amt':
1000.0}
{'INO.': 3, 'Description': 'Copy', 'Quantity': 2, 'Rate': 200.0, 'Amt': 400.0}
XYZ stationary
1. Adding records
2. Modification of records
3. Searching particular details
4. Deleting record
5. Report
6. End of program
Enter your choice : 6
END OF PROGRAM
25
CREATION OF CSV FILES
OUTPUT
Enter employ number 1001
Enter name Ram
Enter Salary 70000
Enter employ number 1002
Enter name Siya
Enter Salary 60000
Enter employ number 1003
Enter name Sam
Enter Salary 55000
Enter employ number 1004
Enter name Ansh
Enter Salary 50000
Enter employ number 1005
Enter name Raj
Enter Salary 75000
26
READING OF CSV FILE
OUTPUT
['Empno', 'Name', 'Salary']
['1001', 'Ram', '70000.0']
['1002', 'Siya', '60000.0']
['1003', 'Sam', '55000.0']
['1004', 'Ansh', '50000.0']
['1005', 'Raj', '75000.0']
27
DATA STRUCTURE
LINEAR SEARCH AND BINARY SEARCH
def Lsearch(l,val):
k=0
for i in l :
if i==val:
k=1
break
return(k)
l=eval(input("Enter the list of numbers "))
m=int(input("Enter the value to be search "))
k=Lsearch(l,m)
if k ==1:
print("Found")
else:
print("Not Found")
Lsearch(l,m)
OUTPUT
Enter the list of numbers [20,55,70,45,80]
Enter the value to be search 70
Found
28
29 (ii.)-Write a function B.Search(L,Val) where L is
passed as list of integers and val is the number to be
search in the list.
def Bsearch(l,val):
k=0
beg=0
last=len(l)-1
while beg <=last:
mid=(beg+last)//2
if l[mid]==val:
k=1
break
elif l[mid]>val:
last=mid-1
elif l[mid]<val:
beg=mid+1
return(k)
l=eval(input("Enter the list of numbers "))
n=int(input("Enter value to be search "))
if Bsearch(l,n)==1:
print("Found")
else:
print("Not found")
Bsearch(l,n)
OUTPUT
Enter the list of numbers [25,40,55,67,90]
Enter value to be search 55
Found
29
BUBBLE SORT AND INSERTION SORT
30 (i.) -Write a function Bsort(L) where L is the list of
integers passed as the arguments. Arrange the data in
ascending order using bubble sort.
def Bsort(L):
for i in range(0,len(L)):
for j in range(0,len(L)-1-i):
if L[j]>L[j+1]:
L[j],L[j+1]=L[j+1],L[j]
print("List in ascending order=",L)
L=eval(input("Enter the list of numbers"))
Bsort(L)
OUTPUT
Enter the list of numbers[20,17,55,10,60,30,12]
List in ascending order= [10, 12, 17, 20, 30, 55, 60]
30 (ii.) -Write a function Isort(L) where L is the list of
integers passed as arguments. Arrange the data in
ascending order using insertion sort.
def Isort(L):
for i in range(1,len(L)):
j=i-1
t=L[i]
while t<L[j] and j>=0:
L[j+1]=L[j]
j=j-1
L[j+1]=t
print("List in ascending order =",L)
L=eval(input("Enter the list of numbers"))
Isort(L)
OUTPUT
Enter the list of numbers[90,45,67,1,11,100,35]
List in ascending order = [1, 11, 35, 45, 67, 90, 100]
30
STACk OPERATIONS
31-Write a function in python Push(), Pop(), Display()
to add , delete and display the names of students from
the list of description considering them to act as push
and pop operations of the stack data structure.
def Push(Name):
x=input("Enter the name of student ")
Name.append(x)
def Pop(Name):
if Name==[]:
print("Underflow")
else:
print("Name removed",Name.pop())
def Display(Name):
if Name==[]:
print("Underflow")
else:
for i in range(len(Name)-1,-1,-1):
print(Name[i])
L=[]
while True:
print("1 Push Name")
print("2 Pop Name")
print("3 Display Name")
print("4 Exit")
ch=int(input("Enter your choice (1-4) "))
if ch==1:
Push(L)
elif ch==2:
Pop(L)
elif ch==3:
Display(L)
elif ch==4:
print("End of stack operation")
break
else:
print("Invalid choice")
31
OUTPUT
1 Push Name
2 Pop Name
3 Display Name
4 Exit
Enter your choice (1-4) 1
Enter the name of student Riya
1 Push Name
2 Pop Name
3 Display Name
4 Exit
Enter your choice (1-4) 1
Enter the name of student Sam
1 Push Name
2 Pop Name
3 Display Name
4 Exit
Enter your choice (1-4) 2
Name removed Sam
1 Push Name
2 Pop Name
3 Display Name
4 Exit
Enter your choice (1-4) 3
Riya
1 Push Name
2 Pop Name
3 Display Name
4 Exit
Enter your choice (1-4) 4
End of stack operation
32
qUEUE OPERATIONS
32 -Write a function Add(Item), Remove(Item) and
Display(Item) to add, delete and display the items from the list.
The structure of the queue consists of itemno, itemName and
Qty.
def Add(ItemName):
IN=int(input("Enter the item number "))
N=input("Enter the item name ")
Q=int(input("Enter the quantity "))
ItemName.append([IN,N,Q])
def Remove(ItemName):
if ItemName==[]:
print("Underflow")
else:
print("Item details removed",ItemName.pop(0))
def Display(ItemName):
if ItemName==[]:
print("Underflow")
else:
for i in range(0,len(ItemName)):
for j in range(0,len(ItemName[i])):
print(ItemName[i][j])
L=[]
while True:
print("1 Add item details")
print("2 Remove item details")
print("3 Display item details")
print("4 Exit")
ch=int(input("Enter your choice (1-4) "))
if ch==1:
Add(L)
elif ch==2:
Remove(L)
elif ch==3:
Display(L)
elif ch==4:
print("End of queue operation")
break
33
else:
print("Invalid choice")
OUTPUT
1 Add item details
2 Remove item details
3 Display item details
4 Exit
Enter your choice (1-4) 1
Enter the item number 101
Enter the item name Pen
Enter the quantity 4
1 Add item details
2 Remove item details
3 Display item details
4 Exit
Enter your choice (1-4) 1
Enter the item number 102
Enter the item name Pencil
Enter the quantity 5
1 Add item details
2 Remove item details
3 Display item details
4 Exit
Enter your choice (1-4) 2
Item details removed [101, 'Pen', 4]
1 Add item details
2 Remove item details
3 Display item details
4 Exit
Enter your choice (1-4) 3
102
Pencil
5
1 Add item details
2 Remove item details
3 Display item details
4 Exit
Enter your choice (1-4) 4
End of queue operation
34
DATABASES
33- INTRODUCTION TO MYSqL
MySQL is written in C and C++. Its SQL parser is written in yacc, but it
uses a home-brewed lexical analyzer. MySQL works on many system
platforms,including AIX, BSDi, FreeBSD, HPUX, ArcaOS, eComStation,
IBM i, IRIX, Linux, macOS, Microsoft Windows, NetBSD, Novell
NetWare, OpenBSD, OpenSolaris, OS/2 Warp, QNX, Oracle
Solaris, Symbian, SunOS, SCO OpenServer, SCO UnixWare, Sanos
and Tru64. A port of MySQL to OpenVMS also exists.[17]
The MySQL server software itself and the client libraries use dual-
licensing distribution. They are offered under GPL version 2, or a
proprietary license.
MySQL is free and open-source software under the terms of the GNU
General Public License, and is also available under a variety
of proprietary licenses. MySQL was owned and sponsored by
the Swedish company MySQL AB, which was bought by Sun
Microsystems (now Oracle Corporation). In 2010, when Oracle
acquired Sun, Widenius forked the open-source MySQL project to
create MariaDB.
36
MYSqL qUERIES
34- TABLE CREATION AND qUERIES
Creating and accessing a database:
Creating table:
37
Selecting all columns:
38
Adding different constraints:
1. Unique constraint
39
4. Default constraint
40
Alter table command:
1. To add a column
41
3. To redefine a column null constraint
4. To rename a column
42
5. To remove a column
43
Joins:
1. Cartesian product
44
2. Equi-join
Aggregate functions:
1. Avg()
45
2. Count()
3. Max()
4. Sum()
46
INTERFACE PYTHON wITH MYSqL
35 - Write a python database connectivity script that –
OUTPUT
47
(ii). Display records of the table
import mysql.connector as mc
mycon = mc.connect(host="localhost", user="root", passwd="2002",
database="students")
if not mycon.is_connected():
print("My sql is not connected")
else:
cur = mycon.cursor()
cur.execute("select * from Data where Name like 'Yuvi' ")
rec = cur.fetchone()
for i in rec:
print(i)
mycon.close()
OUTPUT
import mysql.connector as mc
mycon = mc.connect(host="localhost", user="root", passwd="2002",
database="students")
if not mycon.is_connected():
print("My sql is not connected")
else:
cur = mycon.cursor()
cur.execute("delete from data where grade<'B'")
mycon.commit()
48
cur.execute("select*from data")
rec = cur.fetchall()
for i in rec:
print(i)
mycon.close()
OUTPUT
import mysql.connector as mc
mycon = mc.connect(host="localhost", user="root", passwd="2002",
database="students")
if not mycon.is_connected():
print("My sql is not connected")
else:
cur = mycon.cursor()
cur.execute("update data set grade='A' where name like'Amar'")
mycon.commit()
cur.execute("select*from data")
49
rec = cur.fetchall()
for i in rec:
print(i)
mycon.close()
OUTPUT
50