XII CS Practical File All Programs
XII CS Practical File All Programs
'''
# Write a Program to find the factorial of a number given by the user.
n=int(input("Enter a Number"))
f=1
for i in range(1,n+1):
f=f * i
OUTPUT
Enter a Number : 5
Factorial is 120
'''
#Write a Program to check whether a number is prime or not.
n=int(input("Enter a Number"))
flag=0
for i in range(2,(n//2)+1):
if n%i==0:
flag=1
break
if flag==0:
print("No is Prime")
else:
print("No is Not Prime")
'''
OUTPUT
Enter a Number 13
No is Prime
Enter a Number 14
No is Not Prime
LIST
'''
#Write a Program to find the largest and smallest element in a list along with
their index.
l=[64,91,13,81,22,16,46,10,94,31,33,17,36,79,23,42]
max=l[0]
min=l[0]
indmax, indmin = 0, 0
for i in range(0,len(l)):
if max<l[i]:
max=l[i]
indmax=i
if min>l[i]:
min=l[i]
indmin=i
print ("Maximum is ",max," at index ",indmax)
print ("Minimum is ",min," at index ",indmin)
'''
OUTPUT
l=[64,91,13,81,22,16,46,10,94,31,33,17,36,79,23,42]
Maximum is 94 at index 8
Minimum is 10 at index 7
'''
#Write a Program that obtains the rotation factor and rotates the array as per it.
For example, if the given array is 1,2,3,4,5,6,7 and rotation factor is 2, then
array’s element will shift right by 2 elements and the last two elements will
rotate and come to positions 1 and 2 i.e., array will be 6,7,1,2,3,4,5.
l=[1,2,3,4,5,6,7,8,9,10]
l1 = l[:len(l)-rf]
#l2 = l[len(l)-rf:]
l2 = l[:len(l)-rf-1:-1]
l3 = l2 + l1
OUTPUT
l=[1,2,3,4,5,6,7]
Original List is [1, 2, 3, 4, 5, 6, 7]
Enter Rotation Factor 2
List After Rotation is [6,7,1,2,3,4,5]
STRING
'''
#Write a Program to find the number of vowels, consonants, digits and special
characters in a given sentence.
v, c, d, s = 0, 0, 0, 0
for i in st:
if i in "aeiouAEIOU":
v+=1
elif i in "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ":
c+=1
elif i.isdigit():
d+=1
else:
s+=1
OUTPUT
Vowels 8
Consonants 16
Digits 6
Special 10
#WAF to find the occurrence and position of a string in another string.
'''
s=input("Enter a String")
ch=input("Enter Search String")
flag=0
for i in range(0,len(s)):
if ch==s[i:i+len(ch)]:
print ("Found at ",i)
flag=1
if flag==0:
print ("Not Found")
'''
OUTPUT
'''
def mypower(a,b):
p=1
for i in range(1,b+1):
p=p*a
return p
'''
OTUPUT
def fibo(n):
f1=0
f2=1
for i in range(1,n+1):
f3=f1+f2
print (f2," ")
f1=f2
f2=f3
'''
OUTPUT
>>> fibo(10)
1
1
2
3
5
8
13
21
34
55
'''
# WAF to find the sum of the series 1! + 2! + 3! + 4! +… n!
def fact(n):
f=1
for i in range(1,n+1):
f=f*i
return f
def seriessum(n):
s=0
for i in range(1,n+1):
s = s + fact(i)
return s
'''
OUTPUT
>>> seriessum(5)
153
'''
#WAF to search an element in a list.
def search(l,ele):
for i in range(0,len(l)):
if ele==l[i]:
#print ("Found element at index ",i)
return i
else:
return -1
'''
OUTPUT
>>> l=[15,42,49,87,25,96,72,69,41,17,11]
>>> search(l,25)
4
'''
#WAF to change the case of every 2nd character in a string.
def change(st):
st1=""
for i in range(0,len(st)):
if i%2==0:
st1+=st[i]
else:
if st[i].isupper():
st1 += st[i].lower()
elif st[i].islower():
st1 += st[i].upper()
return st,st1
'''
OUTPUT
>>> st="Education"
>>> change(st)
('Education', 'EDuCaTiOn')
RECURSION
'''
def fact(a):
if a==0:
return 1
else:
return a * fact(a-1)
'''
OUTPUT
'''
fact(5) - 5 * 24 = 120
fact(4) - 4 * 6
fact(3) - 3 * 2
fact(2) - 2 * 1
fact(1) - 1 * 1
fact(0) - 1
'''
#Q. Write a recursive function to find value of a to the power b.
'''
def mypower(a,b):
if b==0:
return 1
else:
return a * mypower(a,b-1)
'''
OUTPUT
'''
mypower(2,3) - 2*mypower(2,2) - 2*4
mypower(2,2) - 2*mypower(2,1) - 2*2
mypower(2,1) - 2*mypower(2,0) - 2*1
mypower(2,0) - 1
'''
#Q. Write a recursive function print the Fibonacci series upto N terms .
'''
def fib(n):
if n==1:
return 0
elif n==2:
return 1
else:
return fib(n-1)+fib(n-2)
'''
OUTPUT
#Q. Write a function using recursion to check if a string provided as parameter
is palindrome.
'''
def strcheckpalin(s):
if len(s)==0:
return True
else:
if s[0]==s[-1]:
return strcheckpalin(s[1:-1])
# or s[1:len(s)-1]
else:
return False
-5 -4 -3 -2 -1
M A D A M
0 1 2 3 4
strcheckpalin(s="MADAM") - strcheckpalin(s[1:-1])
strcheckpalin(s="ADA") - strcheckpalin(s[1:-1])
strcheckpalin(s="D") - strcheckpalin(s[1:-1])
strcheckpalin(s="") - True
'''
#Q. Check if a number is prime or not using a recursive function.
'''
def prim(n,r=2):
if n>r:
if n%r==0:
return False
else:
return prim(n,r+1)
else:
if n==0 or n==1:
return False
else:
return True
prim(n=25,r=2) - prim(25,3)
prim(n=25,r=3) - prim(25,4)
prim(n=25,r=4) - prim(25,5)
prim(n=25,r=5) - return 0
'''
import os
def write_rec_file():
myfile=open("bus.txt","at")
con='y'
while con=='y':
busno=int(input("Enter Bus No"))
bname=input("Enter Bus Name")
passn=int(input("Enter Number of Passengers"))
fare=float(input("Enter Bus Fare"))
myfile.write(mystr)
myfile.flush()
myfile.close()
def read_rec_file():
myfile=open("bus.txt","rt")
st=myfile.readlines()
print (st)
myfile.close()
'''
#other methods to read a file
def search_rec_file1():
myfile=open("bus.txt","rt")
count = 0
str1=input("Enter Bus Name to Search")
for rec in myfile:
if str1 in rec:
count = count + 1
print (rec,end='')
def search_rec_file2(lb,ub):
myfile=open("bus.txt","rt")
count = 0
count = 0
for rec in myfile:
myfile1.write(rec)
count = count + 1
myfile.close()
myfile1.close()
def copy_rec_file():
myfile=open("bus.txt","rt")
myfile1=open("newbus.txt","wt")
count = 0
lb=int(input("Enter Lower range of Passengers"))
ub=int(input("Enter upper range of Passengers"))
def modify_rec_file():
myfile=open("bus.txt","rt")
myfile1=open("newbus.txt","wt")
flag = 0
str1=input("Enter Bus Name to Modify")
myfile1.write(mystr)
myfile1.flush()
else:
myfile1.write(rec)
myfile1.flush()
if flag == 0:
print ("Search String Not Found ")
else:
print ("Record Modified ")
myfile.close()
myfile1.close()
os.remove("bus.txt")
os.rename("newbus.txt","bus.txt")
def delete_rec_file():
myfile=open("bus.txt","rt")
myfile1=open("newbus.txt","wt")
flag = 0
str1=input("Enter Bus Name to Delete")
if flag == 0:
print ("Search String Not Found ")
else:
print ("Record Deleted ")
myfile.close()
myfile1.close()
os.remove("bus.txt")
os.rename("newbus.txt","bus.txt")
while True:
print ("MENU")
print ("1. Write/Append Records to File")
print ("2. Read Records to File")
print ("3. Search Records to File Bus Wise")
print ("4. Search Records to File Range of Passengers Wise")
print ("5. Copy Records From One to Another File")
print ("6. Modify Records in a File")
print ("7. Delete Records in a File")
print ("0. Exit")
ch=int(input("Enter Your Choice"))
if ch==1:
write_rec_file()
if ch==2:
read_rec_file()
if ch==3:
search_rec_file1()
if ch==4:
lb=int(input("Enter Lower range of Passengers"))
ub=int(input("Enter upper range of Passengers"))
search_rec_file2(lp,up)
if ch==5:
copy_rec_file()
if ch==6:
modify_rec_file()
if ch==7:
delete_rec_file()
if ch==0:
print ("Quitting Bye")
break
OUTPUT
MENU
1. Write/Append Records to File
2. Read Records to File
3. Search Records to File Bus Wise
4. Search Records to File Range of Passengers Wise
5. Copy Records From One to Another File
6. Modify Records in a File
7. Delete Records in a File
0. Exit
MENU
1. Write/Append Records to File
2. Read Records to File
3. Search Records to File Bus Wise
4. Search Records to File Range of Passengers Wise
5. Copy Records From One to Another File
6. Modify Records in a File
7. Delete Records in a File
0. Exit
Enter Your Choice2
['101 BSRTC 60 500.0\n', '102 JSRTC 45 250.0\n', '103 UPSRTC 50 500.0\n', '104 OSRTC 40 350.0\n',
'105 MPSRTC 60 550.0\n']
MENU
1. Write/Append Records to File
2. Read Records to File
3. Search Records to File Bus Wise
4. Search Records to File Range of Passengers Wise
5. Copy Records From One to Another File
6. Modify Records in a File
7. Delete Records in a File
0. Exit
Enter Your Choice3
MENU
1. Write/Append Records to File
2. Read Records to File
3. Search Records to File Bus Wise
4. Search Records to File Range of Passengers Wise
5. Copy Records From One to Another File
6. Modify Records in a File
7. Delete Records in a File
0. Exit
Enter Your Choice4
MENU
1. Write/Append Records to File
2. Read Records to File
3. Search Records to File Bus Wise
4. Search Records to File Range of Passengers Wise
5. Copy Records From One to Another File
6. Modify Records in a File
7. Delete Records in a File
0. Exit
Enter Your Choice5
MENU
1. Write/Append Records to File
2. Read Records to File
3. Search Records to File Bus Wise
4. Search Records to File Range of Passengers Wise
5. Copy Records From One to Another File
6. Modify Records in a File
7. Delete Records in a File
0. Exit
Enter Your Choice6
MENU
1. Write/Append Records to File
2. Read Records to File
3. Search Records to File Bus Wise
4. Search Records to File Range of Passengers Wise
5. Copy Records From One to Another File
6. Modify Records in a File
7. Delete Records in a File
0. Exit
Enter Your Choice2
['101 BSRTC 60 500.0\n', '102 JSRTC 45 250.0\n', '103 UPSRTC 50 500.0\n', '1044 OSRTCC 45
365.0\n', '105 MPSRTC 60 550.0\n']
MENU
1. Write/Append Records to File
2. Read Records to File
3. Search Records to File Bus Wise
4. Search Records to File Range of Passengers Wise
5. Copy Records From One to Another File
6. Modify Records in a File
7. Delete Records in a File
0. Exit
Enter Your Choice7
Record Deleted
MENU
1. Write/Append Records to File
2. Read Records to File
3. Search Records to File Bus Wise
4. Search Records to File Range of Passengers Wise
5. Copy Records From One to Another File
6. Modify Records in a File
7. Delete Records in a File
0. Exit
Enter Your Choice2
['101 BSRTC 60 500.0\n', '102 JSRTC 45 250.0\n', '103 UPSRTC 50 500.0\n', '105 MPSRTC 60
550.0\n']
MENU
1. Write/Append Records to File
2. Read Records to File
3. Search Records to File Bus Wise
4. Search Records to File Range of Passengers Wise
5. Copy Records From One to Another File
6. Modify Records in a File
7. Delete Records in a File
0. Exit
Enter Your Choice0
Quitting Bye
BINARY FILE HANDLING
#Program to create binary file to store Rollno and Name, Search any Rollno and display
name if Rollno found otherwise “Rollno not found”
'''
import pickle
student=[]
f=open('student.dat','wb')
ans='y'
while ans.lower()=='y':
roll = int(input("Enter Roll Number :"))
name = input("Enter Name :")
student.append([roll,name])
ans=input("Add More ?(Y)")
pickle.dump(student,f)
f.close()
f=open('student.dat','rb')
student=[]
while True:
try:
student = pickle.load(f)
except EOFError:
break
ans='y'
while ans.lower()=='y':
found=False
r = int(input("Enter Roll number to search :"))
for s in student:
if s[0]==r:
print("## Name is :",s[1], " ##")
found=True
break
if not found:
print("####Sorry! Roll number not found ####")
ans=input("Search more ?(Y) :")
f.close()
'''
OUTPUT
'''
import pickle
student=[]
f=open('student.dat','wb')
ans='y'
while ans.lower()=='y':
roll = int(input("Enter Roll Number :"))
name = input("Enter Name :")
marks = int(input("Enter Marks :"))
student.append([roll,name,marks])
ans=input("Add More ?(Y)")
pickle.dump(student,f)
f.close()
f=open('student.dat','rb+')
student=[]
while True:
try:
student = pickle.load(f)
except EOFError:
break
ans='y'
while ans.lower()=='y':
found=False
r = int(input("Enter Roll number to update :")) for s in student:
if s[0]==r:
print("## Name is :",s[1], " ##")
print("## Current Marks is :",s[2]," ##")
m = int(input("Enter new marks :"))
s[2]=m
print("## Record Updated ##")
found=True
break
if not found:
print("####Sorry! Roll number not found ####")
ans=input("Update more ?(Y) :")
f.close()
'''
OUTPUT
Enter Roll Number :1
Enter Name :Amit
Enter Marks :99
Add More ?(Y)y
while True:
print ("MENU")
print ("1. Write/Append Records to File")
print ("2. Read Records to File")
print ("3. Search Records to File Roll Wise")
print ("4. Search Records to File Range of Marks Wise")
print ("5. Copy Records From One to Another File")
print ("6. Modify Records in a File")
print ("7. Delete Records in a File")
print ("0. Exit")
ch=int(input("Enter Your Choice"))
if ch==1:
insert_rec_binary()
if ch==2:
read_rec_binary()
if ch==3:
search_rec_binary_roll()
if ch==4:
lb=int(input("Enter Lower range of Marks"))
ub=int(input("Enter upper range of Marks"))
search_rec_binary_marks(lb,ub)
if ch==5:
lb=int(input("Enter Lower range of Marks"))
ub=int(input("Enter upper range of Marks"))
copy_rec_binary_marks(lb,ub)
if ch==6:
r=int(input("Enter RollNo to Modify"))
m=int(input("Enter Marks to Update"))
update_rec_binary(r,m)
if ch==7:
r=int(input("Enter RollNo to Delete"))
delete_rec_binary(r)
if ch==0:
print ("Quitting Bye")
break
OUTPUT
MENU
1. Write/Append Records to File
2. Read Records to File
3. Search Records to File Roll Wise
4. Search Records to File Range of Marks Wise
5. Copy Records From One to Another File
6. Modify Records in a File
7. Delete Records in a File
0. Exit
Enter Your Choice1
Enter roll number:1
Enter Name:ABCD
Enter Marks45
MENU
1. Write/Append Records to File
2. Read Records to File
3. Search Records to File Roll Wise
4. Search Records to File Range of Marks Wise
5. Copy Records From One to Another File
6. Modify Records in a File
7. Delete Records in a File
0. Exit
Enter Your Choice2
Roll Num: 1
Name: ABCD
Marks: 45
Roll Num: 2
Name: XYZW
Marks: 65
Roll Num: 3
Name: PQRS
Marks: 85
Roll Num: 4
Name: MNOP
Marks: 75
Roll Num: 5
Name: JKLF
Marks: 80
MENU
1. Write/Append Records to File
2. Read Records to File
3. Search Records to File Roll Wise
4. Search Records to File Range of Marks Wise
5. Copy Records From One to Another File
6. Modify Records in a File
7. Delete Records in a File
0. Exit
Enter Your Choice3
MENU
1. Write/Append Records to File
2. Read Records to File
3. Search Records to File Roll Wise
4. Search Records to File Range of Marks Wise
5. Copy Records From One to Another File
6. Modify Records in a File
7. Delete Records in a File
0. Exit
Enter Your Choice4
MENU
1. Write/Append Records to File
2. Read Records to File
3. Search Records to File Roll Wise
4. Search Records to File Range of Marks Wise
5. Copy Records From One to Another File
6. Modify Records in a File
7. Delete Records in a File
0. Exit
Enter Your Choice5
MENU
1. Write/Append Records to File
2. Read Records to File
3. Search Records to File Roll Wise
4. Search Records to File Range of Marks Wise
5. Copy Records From One to Another File
6. Modify Records in a File
7. Delete Records in a File
0. Exit
Enter Your Choice6
MENU
1. Write/Append Records to File
2. Read Records to File
3. Search Records to File Roll Wise
4. Search Records to File Range of Marks Wise
5. Copy Records From One to Another File
6. Modify Records in a File
7. Delete Records in a File
0. Exit
Enter Your Choice2
Roll Num: 1
Name: ABCD
Marks: 45
Roll Num: 2
Name: XYZW
Marks: 90
Roll Num: 3
Name: PQRS
Marks: 85
Roll Num: 4
Name: MNOP
Marks: 75
Roll Num: 5
Name: JKLF
Marks: 80
MENU
1. Write/Append Records to File
2. Read Records to File
3. Search Records to File Roll Wise
4. Search Records to File Range of Marks Wise
5. Copy Records From One to Another File
6. Modify Records in a File
7. Delete Records in a File
0. Exit
Enter Your Choice7
Enter RollNo to Delete4
MENU
1. Write/Append Records to File
2. Read Records to File
3. Search Records to File Roll Wise
4. Search Records to File Range of Marks Wise
5. Copy Records From One to Another File
6. Modify Records in a File
7. Delete Records in a File
0. Exit
Enter Your Choice2
Roll Num: 1
Name: ABCD
Marks: 45
Roll Num: 2
Name: XYZW
Marks: 90
Roll Num: 3
Name: PQRS
Marks: 85
Roll Num: 5
Name: JKLF
Marks: 80
MENU
1. Write/Append Records to File
2. Read Records to File
3. Search Records to File Roll Wise
4. Search Records to File Range of Marks Wise
5. Copy Records From One to Another File
6. Modify Records in a File
7. Delete Records in a File
0. Exit
Enter Your Choice0
Quitting Bye
RANDOM FILE HANDLING
#Program to read and display file content line by line with each word separated by “#”
'''
f = open("file1.txt")
for line in f:
words = line.split()
for w in words:
print(w+'#',end='')
print()
f.close()
'''
OUTPUT
India#is#my#country#
I#love#python#
Python#learning#is#fun#
#Program to read the content of file and display the total number of consonants,
uppercase, vowels and lower case characters‟
'''
f = open("file1.txt")
v, c, u, l, o = 0, 0, 0, 0, 0
data = f.read()
vowels=['a','e','i','o','u']
for ch in data:
if ch.isalpha():
if ch.lower() in vowels:
v+=1
else:
c+=1
if ch.isupper():
u+=1
elif ch.islower():
l+=1
elif ch!=' ' and ch!='\n':
o+=1
f.close()
'''
OUTPUT
Total Vowels in file 16
Total Consonants in file 30
Total Capital letters in file 2
Total Small letters in file 44
Total Other than letters 4
CSV FILE HANDLING
#Program to create CSV file and store empno, name, salary and search any empno and
display name, salary and if not found appropriate message.
'''
import csv
with open('myfile.csv',mode='a')as csvfile:
mywriter = csv.writer(csvfile,delimiter=',')
ans='y'
while ans.lower()=='y':
eno=int(input("Enter Employee Number "))
name=input("Enter Employee Name ")
salary=int(input("Enter Employee Salary :"))
mywriter.writerow([eno,name,salary])
print("## Data Saved... ##")
ans=input("Add More ?")
ans='y'
with open('myfile.csv',mode='r') as csvfile:
myreader = csv.reader(csvfile,delimiter=',')
while ans=='y':
found=False
e = int(input("Enter Employee Number to search :"))
for row in myreader:
if len(row)!=0:
if int(row[0])==e:
print("============================")
print("NAME :",row[1])
print("SALARY :",row[2])
found=True
break
if not found:
print("==========================")
print(" EMPNO NOT FOUND")
print("==========================")
ans = input("Search More ? (Y)")
OUTPUT
'''
def s_push(s,item):
s.append(item)
def s_pop(s):
if (s==[]):
print ("Stack Empty UNDERFLOW")
else:
print ("Deleted element is : ",s.pop())
def s_display(s):
if (s==[]):
print ("Stack Empty")
else:
print (s[::-1])
s=[]
c="y"
while (c=="y"):
print ("1. PUSH")
print ("2. POP ")
print ("3. Display")
choice=int(input("Enter your choice: "))
if (choice==1):
a=input("Enter any number :")
s_push(s,a)
elif (choice==2):
s_pop(s)
elif (choice==3):
s_display(s)
c=input("Do you want to continue or not? ")
'''
OUTPUT:
>>>
1. PUSH
2. POP
3. Display
Enter your choice: 2
Stack Empty UNDERFLOW
Do you want to continue or not? y
1.PUSH
2.POP
3.Display
Enter your choice: 1
Enter any number :100
Do you want to continue or not? y
1. PUSH
2. POP
3. Display
Enter your choice: 1
Enter any number :200
Do you want to continue or not? y
1. PUSH
2. POP
3. Display
Enter your choice: 1
Enter any number :300
Do you want to continue or not? y
1. PUSH
2. POP
3. Display
Enter your choice: 3
300
200
100
QUEUE
'''
def s_insert(a,item):
a.append(item)
def s_remove(a):
if (a==[]):
print("Queue Empty UNDERFLOW")
else:
print ("deleted element is:",a[0])
del a[0]
def s_display(a):
l=len(a)
for i in range(0,l):
print (a[i])
a=[]
c='y'
while c=='y':
print ("1. INSERT")
print ("2. DELETE ")
print ("3. Display")
choice=int(input("enter your choice "))
if (choice==1):
b=int(input("enter new number "))
s_insert(a,b)
elif (choice==2):
s_remove(a)
elif (choice==3):
s_display(a)
else:
print("wrong input")
c=input("do you want to continue or not ")
'''
OUTPUT:
>>>
1. INSERT
2. DELETE
3. Display
Enter your choice: 2
Queue Empty UNDERFLOW
Do you want to continue or not? y
1.INSERT
2.DELETE
3.Display
Enter your choice: 1
Enter any number :100
Do you want to continue or not? y
1. INSERT
2. DELETE
3. Display
Enter your choice: 1
Enter any number :200
Do you want to continue or not? y
1. INSERT
2. DELETE
3. Display
Enter your choice: 1
Enter any number :300
Do you want to continue or not? y
1. INSERT
2. DELETE
3. Display
Enter your choice: 3
100
200
300
1. INSERT
2. DELETE
3. Display
Enter your choice: 2
Deleted element is :100
Do you want to continue or not? y
Table: EMP
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
7369 SMITH CLERK 7902 17-Dec-80 800 20
7499 ALLEN SALESMAN 7698 20-Feb-81 1600 300 30
7521 WARD SALESMAN 7698 22-Feb-81 1250 500 30
7566 JONES MANAGER 7839 2-Apr-81 2975 20
7654 MARTIN SALESMAN 7698 28-Sep-81 1250 1400 30
7698 BLAKE MANAGER 7839 1-May-81 2850 30
7782 CLARK MANAGER 7839 9-Jun-81 2450 10
7788 SCOTT ANALYST 7566 19-Apr-87 3000 20
7839 KING PRESIDENT 17-Nov-81 5000 10
7844 TURNER SALESMAN 7698 8-Sep-81 1500 0 30
7876 ADAMS CLERK 7788 23-May-87 1100 20
7900 JAMES CLERK 7698 3-Dec-81 950 30
7902 FORD ANALYST 7566 3-Dec-81 3000 20
7934 MILLER CLERK 7782 23-Jan-82 1300 10
import mysql.connector
mydb=mysql.connector.connect(host='localhost',
user='root',
password='kvhec',
database='student',
charset='utf8'
)
mycursor=mydb.cursor()
resultset=mycursor.fetchall()
#print (resultset)
for rec in resultset:
print (rec)
'''
#Program 2 : Display all records of EMP table of job='Clerk'
import mysql.connector
mydb=mysql.connector.connect(host='localhost',
user='root',
password='kvhec',
database='student',
charset='utf8'
)
mycursor=mydb.cursor()
'''
#Program 3 : Display all records of EMP table of job as entered by user
import mysql.connector
mydb=mysql.connector.connect(host='localhost',
user='root',
password='kvhec',
database='student',
charset='utf8'
)
mycursor=mydb.cursor()
mycursor.execute(sqlstr)
resultset=mycursor.fetchall()
#print (resultset)
mycursor.execute(mystr)
mydb.commit()
'''
'''
#Program 1 : Update a record to EMP table
import mysql.connector
mydb=mysql.connector.connect(host='localhost',
user='root',
password='kvhec',
database='student',
charset='utf8'
)
mycursor=mydb.cursor()
mycursor.execute(mystr)
mydb.commit()
'''
'''
#Program 1 : Delete a record to EMP table
import mysql.connector
mydb=mysql.connector.connect(host='localhost',
user='root',
password='kvhec',
database='student',
charset='utf8'
)
mycursor=mydb.cursor()
mycursor.execute(mystr)
mydb.commit()
'''
#Program to connect with database and store record of employee and display records.
choice=None
while choice!=0:
print("1. ADD RECORD ")
print("2. DISPLAY RECORD ")
print("0. EXIT")
1. ADD RECORD
2. DISPLAY RECORD
0. EXIT
Enter Choice :1
Enter Employee Number :1
Enter Name :AMIT
Enter Department :SALES
Enter Salary :9000
## Data Saved ##
1. ADD RECORD
2. DISPLAY RECORD
0. EXIT
Enter Choice :1
Enter Employee Number :2
Enter Name :NITIN
Enter Department :IT
Enter Salary :80000
## Data Saved ##
1. ADD RECORD
2. DISPLAY RECORD
0. EXIT
Enter Choice :2
EMPNO NAME DEPARTMENT SALARY
1 AMIT SALES 9000
2 NITIN IT 80000
1. ADD RECORD
2. DISPLAY RECORD
0. EXIT
Enter Choice :0 ## Bye!! ##
PYTHON DATABASE CONNECTIVITY
#Program to connect with database and store record of employee and display records.
choice=None
while choice!=0:
print("1. ADD RECORD ")
print("2. DISPLAY RECORD ")
print("0. EXIT")
1. ADD RECORD
2. DISPLAY RECORD
0. EXIT
Enter Choice :1
Enter Employee Number :1
Enter Name :AMIT
Enter Department :SALES
Enter Salary :9000
## Data Saved ##
1. ADD RECORD
2. DISPLAY RECORD
0. EXIT
Enter Choice :1
Enter Employee Number :2
Enter Name :NITIN
Enter Department :IT
Enter Salary :80000
## Data Saved ##
1. ADD RECORD
2. DISPLAY RECORD
0. EXIT
Enter Choice :2
EMPNO NAME DEPARTMENT SALARY
1 AMITSALES 9000
2 NITIN IT 80000
1. ADD RECORD
2. DISPLAY RECORD
0. EXIT
Enter Choice :0 ## Bye!! ##
#Program to connect with database and search employee number in table employee and
display record, if empno not found display appropriate message.
print("#"*40)
print("EMPLOYEE SEARCHING FORM")
print("#"*40)
print("\n\n") ans='y'
while ans.lower()=='y':
eno = int(input("ENTER EMPNO TO SEARCH :"))
query="select * from employee where empno={}".format(eno)
cur.execute(query)
result = cur.fetchall()
if cur.rowcount==0:
print("Sorry! Empno not found ")
else:
print("%10s"%"EMPNO", "%20s"%"NAME","%15s"%"DEPARTMENT",
"%10s"%"SALARY")
for row in result:
print("%10s"%row[0],"%20s"%row[1],"%15s"%row[2],"%10s"%row[3])
ans=input("SEARCH MORE (Y) :")
OUTPUT
########################################
EMPLOYEE SEARCHING FORM
########################################
while ans.lower()=='y':
eno = int(input("ENTER EMPNO TO UPDATE :"))
query="select * from employee where empno={}".format(eno)
cur.execute(query)
result = cur.fetchall()
if cur.rowcount==0:
print("Sorry! Empno not found ")
else:
print("%10s"%"EMPNO","%20s"%"NAME", "%15s"%"DEPARTMENT",
"%10s"%"SALARY")
for row in result:
print("%10s"%row[0],"%20s"%row[1],"%15s"%row[2],"%10s"%row[3])
choice=input("\n## ARE YOUR SURE TO UPDATE ? (Y) :")
if choice.lower()=='y':
print("== YOU CAN UPDATE ONLY DEPT AND SALARY ==")
print("== FOR EMPNO AND NAME CONTACT ADMIN ==")
d = input("ENTER NEW DEPARTMENT,(LEAVE BLANK IF NOT
WANT TO CHANGE )")
if d=="":
d=row[2]
try:
s = int(input("ENTER NEW SALARY,(LEAVE BLANK IF
NOT WANT TO CHANGE ) "))
except:
s=row[3]
query="update employee set dept='{}',salary={} where
empno={}".format (d,s,eno)
cur.execute(query)
con.commit()
print("## RECORD UPDATED ## ")
ans=input("UPDATE MORE (Y) :")
OUTPUT
########################################
EMPLOYEE UPDATION FORM
########################################
while ans.lower()=='y':
eno = int(input("ENTER EMPNO TO DELETE :"))
query="select * from employee where empno={}".format(eno) cur.execute(query)
result = cur.fetchall()
if cur.rowcount==0:
print("Sorry! Empno not found ")
else:
print("%10s"%"EMPNO","%20s"%"NAME", "%15s"%"DEPARTMENT",
"%10s"%"SALARY")
for row in result:
print("%10s"%row[0],"%20s"%row[1],"%15s"%row[2],"%10s"%row[3])
choice=input("\n## ARE YOUR SURE TO DELETE ? (Y) :")
if choice.lower()=='y':
query="delete from employee where empno={}".format(eno)
cur.execute(query)
con.commit()
print("=== RECORD DELETED SUCCESSFULLY! ===")
ans=input("DELETE MORE ? (Y) :")
OUTPUT
########################################
EMPLOYEE DELETION FORM
########################################
import random
import time
while play=='y':
try:
while True:
for i in range(10):
print()
n = random.randint(1,6)
print(n,end='')
time.sleep(.00001)
except KeyboardInterrupt:
print("Your Number is :”, n)
ans=input("Play More? (Y) :”)
if ans.lower()!='y':
play='n'
break
OUTPUT
Your Number is : 4
Play More? (Y) :y
Your Number is : 3
Play More? (Y) :y
Your Number is : 2
Play More? (Y) :n
#Program to take 10 sample phishing email, and find the most common word occurring
phishingemail=[
"[email protected]",
"[email protected]",
"[email protected]”,
"[email protected]”,
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]"
“[email protected]”,
"[email protected]”]
myd={}
for e in phishingemail:
x=e.split('@')
for w in x:
if w not in myd:
myd[w]=1
else:
myd[w]+=1
key_max = max(myd,key=myd.get)
print("Most Common Occuring word is :",key_max)
OUTPUT
Most Common Occuring word is : mymoney.com
#Program to create 21 Stick Game so that computer always wins
Rule of Game (Total Sticks = 21):
1) User and Computer both can pick stick one by one
2) Maximum stick both can pick is 4 i.e. 1 to 4
3) Anyone with last stick will be the looser
def PrintStick(n):
print("o "*n)
print("| "*n)
print("| "*n)
print("| "*n)
print("| "*n)
TotalStick=21
win=False
humanPlayer=True
while win==False:
if humanPlayer==True:
print("You Can Pick stick between 1 to 4")
userPick=0
while userPick<=0 or userPick>4:
userPick = int(input(playerName +": Enter Number of Stick to Pick"))
TotalStick = TotalStick – userPick
humanPlayer=False
PrintStick(TotalStick)
print("*"*60)
input("Press any key...")
else:
computerPick = (5-userPick)
print("Computer Picks : ",computerPick," Sticks ")
TotalStick=TotalStick –computerPick
PrintStick(TotalStick)
if TotalStick==1:
print("## WINNER : COMPUTER ##")
win=True
print("*"*60)
input("Press any key...")
humanPlayer=True
OUTPUT
NETWORK DEVICES
MODEM
HUB
SWITCH
REPEATER
BRIDGE
ROUTER
GATEWAY
WiFi CARD
MESH TOPOLOGY
RING TOPOLOGY
BUS TOPOLOGY
STAR TOPOLOGY
TRANSMISSION MEDIA
UTP
COAXIAL CABLE
Table: DETAILS
DNO DNAME LOC
10 MARKETING MUMBAI
20 FINANCE DELHI
30 PRODUCTION PUNE
Table: EMP
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
7369 SMITH CLERK 7902 17-Dec-80 800 20
7499 ALLEN SALESMAN 7698 20-Feb-81 1600 300 30
7521 WARD SALESMAN 7698 22-Feb-81 1250 500 30
7566 JONES MANAGER 7839 2-Apr-81 2975 20
7654 MARTIN SALESMAN 7698 28-Sep-81 1250 1400 30
7698 BLAKE MANAGER 7839 1-May-81 2850 30
7782 CLARK MANAGER 7839 9-Jun-81 2450 10
7788 SCOTT ANALYST 7566 19-Apr-87 3000 20
7839 KING PRESIDENT 17-Nov-81 5000 10
7844 TURNER SALESMAN 7698 8-Sep-81 1500 0 30
7876 ADAMS CLERK 7788 23-May-87 1100 20
7900 JAMES CLERK 7698 3-Dec-81 950 30
7902 FORD ANALYST 7566 3-Dec-81 3000 20
7934 MILLER CLERK 7782 23-Jan-82 1300 10
SELECT WHERE
i) To display the records of all employees.
ii) To display the records of employee name SCOTT.
iii) To display the records of all employees who work as SALESMAN.
iv) To display the records of all employees who work in DEPTNO 20
v) To display the records of all employees who get a salary less than 2500
AND OR
i) To display the records of all employees who work as SALESMAN in DEPTNO 20
ii) To display the records of all employees not working in DEPTNO 10 and joined before 01-01-1980
iii) To display the records of all employees who are SALESMAN and get a salary less than 2500
iv) To display the records of all employees getting SALARY between 1000 and 1200
v) To display the records of all employees who have joining date between 1981-01-01 to 1981-12-31.
vi) To display the record of all employees who have jobs as SALESMAN AND MANAGER.
vii) To display the records of all employees who work in DEPTNO 10 and 20
BETWEEN ( > < )
i) To display the record of all employees who have salary in the range of 800 to 1500
ii) To display the record of all employees who joined in the period between 01-01-1980 to 01-01-1981
iii) To display the record of all employees who have commission from 0 to 200.
LIST (IN)
i) To display the record of all employees who have jobs as SALESMAN, MANAGER and ANALYST
ii) To display the record of all employees who work in department no 10,20,30
iii) To display the record of all employees who salaries as 800,1000 and 1200
SELECT DISTINCT
i) To display the unique types of JOB done by the employees.
ii) To display the unique types of DEPTNO of employees.
PATTERN (LIKE % _)
i) To Display the records of all employees whose names start with S.
ii) To Display the records of all employees whose JOB have the letters NAG in them.
iii) To Display the records of all employees whose names have E as their second last character.
NULL
i) To display the details of the employee who does not have a manager
ii) To display the list all employees who get a commission
iii) To display the list all employees who do not get a commission
NOT
i) To display the Records of all employees who do not receive any commission.
ii) To display the Records of all employees who do not work in DEPTNO 10
iii) To display the Records of all employees who do not get alary in between 800 to 1200
SELECT ROWS (ORDER BY)
i) To display the ENAME, JOB and MGR CODE of all the employees sorted in descending order of SALARY.
ii) To display the EMPLOYEE NO, SALARY and HIREDATE of all the employees sorted in ascending order of DEPTNO
iii) To display the ENAME, JOB and COMM of all the employees sorted in ascending order of HIREDATE
SCALER EXPRESSIONS
i) To display the ENAME, SAL, and Yearly Sal (SAL*12) of all employees.
ii) To display the ENAME, SALARY, COMM, SALARY + COMM AS “TOTAL” of all employees in the following format.
ENAME SAL COMM TOTAL ( SALARY + COMM)
SMITH 800 800
ALLEN 1600 300 1600
WARD 1250 500 1250
JONES 2975 2975
iii) To display the ENAME, JOB, MIDDLE (4 characters starting from 3rd Position of JOB) of all employees in the following format.
ENAME JOB MIDDLE
SMITH CLERK ERK
ALLEN SALESMAN LESM
WARD SALESMAN LESM
AGGREGATE FUNCTIONS
i) Find the max SALARY of all employees
ii) Find the min Salary in deptno 10
iii) Find the sum of all Salary for all employees in deptno 10 and 20
iv) Find the average of Salary of Department 10 and 20
v) Find the number of employees in Deptno 10 and 20
CREATE
i) Create the table EMPNEW with datatypes and constraint as provided
COLUMN NAME DATA TYPE LENGTH CONSTRAINT
EMPNO Integer 5 PRIMARY KEY
ENAME Character 20
JOB Character 20
MGR Integer 3
HIREDATE Date NOT NULL
SAL Float 7,2 Should not be less than zero
COMM Integer 4
DEPTNO Integer 2 References DETAILS (DNO)
GROUP BY
i) Show the number of employees in each Department
ii) Show the average Salary of the employees in department 10 and 20
iii) Show the min HIREDATE of each Deptno where minimum HIREDATE is greater than 22-Feb-1998
JOIN
i) To display the ENAME, DEPTNO AND DNAME of all employees
ii) To display the ENAME, DNAME and LOC of all employees who are in DNAME FIN
iii) To display the ENAME, HIREDATE and LOC of all employees of DNAME MKT
ANSWERS
SELECT WHERE
i) SELECT * FROM EMP;
ii) SELECT * FROM EMP WHERE ENAME=’SCOTT’;
iii) SELECT * FROM EMP WHERE JOB=’SALESMAN’;
iv) SELECT * FROM EMP WHERE DEPTNO=10;
v) SELECT * FROM EMP WHERE SAL<=2500;
AND OR
i) SELECT * FROM EMP WHERE JOB=’SALESMAN’ AND DEPTNO=20;
ii) SELECT * FROM EMP WHERE DEPTNO=20 AND HIREDATE<=’1980-01-01’;
iii) SELECT * FROM EMP WHERE JOB=’SALESMAN’ AND SAL<=2500;
LIST
i) SELECT * FROM EMP WHERE JOB IN (‘SALESMAN’, ‘MANAGER’, ‘ANALYST’);
ii) SELECT * FROM EMP WHERE DEPTNO IN (10, 20, 30);
iii) SELECT * FROM EMP WHERE SAL IN (800, 1000, 1200);
SELECT DISTINCT
i) SELECT DISTINCT JOB FROM EMP;
ii) SELECT DISTINCT DEPTNO FROM EMP;
PATTERN
i) SELECT * FROM EMP WHERE ENAME LIKE ‘S%’;
ii) SELECT * FROM EMP WHERE JOB LIKE ‘%NAG%’;
iii) SELECT * FROM EMP WHERE ENAME LIKE ‘%E_’;
NULL
i) SELECT * FROM EMP WHERE MGR IS NULL;
ii) SELECT * FROM EMP WHERE COMM IS NOT NULL;
iii) SELECT * FROM EMP WHERE COMM IS NULL;
NOT
i) SELECT * FROM EMP WHERE COMM IS NULL;
ii) SELECT * FROM EMP WHERE NOT DEPTNO = 10;
iii) SELECT * FROM EMP WHERE NOT SAL BETWEEN 800 AND 1200;
SELECT ROWS
i) SELECT ENAME, JOB AND MGR FROM EMP ORDER BY SAL DESC.
ii) SELECT EMPNO, SAL, HIREDATE FROM EMP ORDER BY DEPTNO ASC;
iii) SELECT ENAME, JOB, COMM FROM EMP ORDER BY HIREDATE ASC;
SCALER EXPRESSIONS
i) SELECT ENAME,SAL,SAL*12 “YEARLY SAL” FROM EMP;
ii) SELECT ENAME, SAL, COMM, SAL + COMM “TOTAL” FROM EMP;
iii) SELECT ENAME, JOB, MIDDLE (3,4) FROM EMP;
AGGREGATE FUNCTIONS
i) SELECT MAX(SAL) FROM EMP;
ii) SELECT MIN(SAL) FROM EMP WHERE DEPTNO=10;
iii) SELECT SUM(SAL) FROM EMP WHERE DEPTNO IN (10,20);
iv) SELECT AVG(SAL) FROM EMP WHERE DEPTNO IN (10,20);
v) SELECT COUNT(*) FROM EMP WHERE DEPTNO IN (10,20);
CREATE
CREATE TABLE EMPNEW (
EMPNO INT PRIMARY KEY,
ENAME VARCHAR(20) ,
JOB VARCHAR(20),
MGR INT,
HIREDATE DATE NOT NULL,
SAL INT CHECK (SAL>0),
COMM INT,
DEPTNO INT,
INDEX DET_DNO (DEPTNO),
FOREIGN KEY (DEPTNO) REFERENCES DETAILS(DNO) ON DELETE CASCADE
)ENGINE=INNODB;
INSERT
INSERT INTO EMPNEW VALUES (7369,”SMITH”,”CLERK”, 7902, “1980-12-17”, 800, NULL, 20);
INSERT INTO EMPNEW VALUES (7499,”ALLEN”,”SALESMAN”, 7698, “1981-02-20”, 1600, 300, 30);
UPDATE
i) UPDATE EMPNEW SET DEPTNO=10 WHERE ENAME = “FORD”;
ii) UPDATE EMPNEW SET SAL=SAL + SAL *5/100;
iii) UPDATE EMPNEW SET COMM=SAL * 10/100 WHERE ENAME = “BLAKE”;
DELETE
i) DELETE FROM EMPNEW WHERE ENAME = “BLAKE”;
ii) DELETE FROM EMPNEW DEPTNO =10;
ALTER
i) ALTER TABLE EMPNEW ADD (PHONE CHAR(10));
ii) ALTER TABLE EMPNEW MODIFY ENAME CHAR(30);
iii) ALTER TABLE EMPNEW DROP COLUMN PHONE;
DROP
i) DROP TABLE EMPNEW;
GROUP BY
i) SELECT COUNT(*) FROM EMP GROUP BY DEPTNO;
ii) SELECT AVG(SAL) FROM EMP WHERE DEPTNO IN (10,20) GROUP BY DEPTNO;
iii) SELECT MIN(HIREDATE) FROM EMP WHERE GROUP BY DEPTNO HAVING MIN(HIREDATE)>=”1998-02-22”;
JOIN
i) SELECT ENAME, DEPTNO, DNAME FROM EMP, DETAILS WHERE EMP.DEPTNO=DETAILS.DEPTNO;
ii) SELECT ENAME, DNAME, LOC FROM EMP, DETAILS WHERE EMP.DEPTNO=DETAILS.DEPTNO AND DAME=“FIN”;
iii) SELECT ENAME, HIREDATE, LOC FROM EMP, DETAILS WHERE EMP.DEPTNO=DETAILS.DEPTNO AND DNAME=”MKT”;