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

XII CS Practical File All Programs

The document contains various Python programs demonstrating control flow, looping, list manipulation, string processing, functions, recursion, and file handling. Each section includes code snippets for tasks such as calculating factorials, checking for prime numbers, finding maximum and minimum in a list, and managing records in a file. The document serves as a comprehensive guide for implementing basic programming concepts in Python.

Uploaded by

kumarmohak70
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 views71 pages

XII CS Practical File All Programs

The document contains various Python programs demonstrating control flow, looping, list manipulation, string processing, functions, recursion, and file handling. Each section includes code snippets for tasks such as calculating factorials, checking for prime numbers, finding maximum and minimum in a list, and managing records in a file. The document serves as a comprehensive guide for implementing basic programming concepts in Python.

Uploaded by

kumarmohak70
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/ 71

FLOW OF CONTROL : LOOPING

'''
# 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

print ("Factorial is ",f)


'''

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]

print ("Original List is ",l)

rf=int(input("Enter Rotation Factor"))

l1 = l[:len(l)-rf]
#l2 = l[len(l)-rf:]
l2 = l[:len(l)-rf-1:-1]

l3 = l2 + l1

print ("List After Rotation is ",l3)


'''

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.

st="My address is block no 243/2/1 road no 2"

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

print ("Vowels ",v)


print ("Consonants ",c)
print ("Digits ",d)
print ("Special ",s)
'''

OUTPUT

st="My address is block no 243/2/1 road no 2"

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

Enter a String EDUCATION


Enter Search String CAT
Found at 3
FUNCTION
b
#WAF to find the value of a where a and b are values provided by the user.

'''
def mypower(a,b):
p=1
for i in range(1,b+1):
p=p*a

return p
'''

OTUPUT

print (“Output is :”, mypower(2,3))


Output is 8
'''
#WAF to print the Fibonacci series 1, 1, 2, 3, 5, 8, … 144.

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

#Q. Write a function to find the Factorial of a number recursively where n is


supplied as parameter to the function.

'''
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

#Function to Write Records to a File

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

mystr=str(busno)+" "+bname+" "+str(passn)+" "+str(fare)+"\n"

myfile.write(mystr)
myfile.flush()

con=input("Do You want to add more Records")

myfile.close()

#Function to read contents of a file

def read_rec_file():
myfile=open("bus.txt","rt")
st=myfile.readlines()
print (st)
myfile.close()

'''
#other methods to read a file

# read function reads entire content to one string


myfile=open("bus.txt","rt")
st=myfile.read()
print (st)
myfile.close()

#Reads one record at a time


myfile=open("bus.txt","rt")
for rec in myfile:
print (rec)
myfile.close()
'''

#Function(1) to Read Records from 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='')

print ("Search String Found ",count," times")


myfile.close()

#Function(2) to Read Records from a File

def search_rec_file2(lb,ub):
myfile=open("bus.txt","rt")
count = 0

for rec in myfile:


mylst=rec.split()
if int(mylst[2])>=lb and int(mylst[2])<=ub:
count = count + 1
print (rec,end='')

print ("Search String Found ",count," times")


myfile.close()

#Program to Copy Records from one File to another


'''
myfile=open("bus.txt","rt")
myfile1=open("newbus.txt","wt")

count = 0
for rec in myfile:
myfile1.write(rec)
count = count + 1

myfile.close()
myfile1.close()

print ("No of lines written to new file is", count)


'''

#Function to Copy Records from one File to another based on a condition

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

for rec in myfile:


mylst=rec.split()
if int(mylst[2])>=lb and int(mylst[2])<=ub:
myfile1.write(rec)
count = count + 1

print ("No of lines written to new file is", count)


myfile.close()
myfile1.close()

#Function to Modify Records in a File

def modify_rec_file():
myfile=open("bus.txt","rt")
myfile1=open("newbus.txt","wt")

flag = 0
str1=input("Enter Bus Name to Modify")

for rec in myfile:


if str1 in rec:
flag = 1
print ("Record to be Modified is",rec)
print ("Enter New Records")
busno=int(input("Enter Bus No"))
bname=input("Enter Bus Nname")
passn=int(input("Enter Number of Passengers"))
fare=float(input("Enter Bus Fare"))

mystr=str(busno)+" "+bname+" "+str(passn)+" "+str(fare)+"\n"

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

#Function to Delete Records in a File

def delete_rec_file():
myfile=open("bus.txt","rt")
myfile1=open("newbus.txt","wt")
flag = 0
str1=input("Enter Bus Name to Delete")

for rec in myfile:


if not (str1 in rec):
myfile1.write(rec)
myfile1.flush()
else:
flag = 1
print ("Record to be Deleted is",rec)

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

Enter Your Choice1

Enter Bus No101


Enter Bus NameBSRTC
Enter Number of Passengers60
Enter Bus Fare500
Do You want to add more Recordsy

Enter Bus No102


Enter Bus NameJSRTC
Enter Number of Passengers45
Enter Bus Fare250
Do You want to add more Recordsy

Enter Bus No103


Enter Bus NameUPSRTC
Enter Number of Passengers50
Enter Bus Fare500
Do You want to add more Recordsy

Enter Bus No104


Enter Bus NameOSRTC
Enter Number of Passengers40
Enter Bus Fare350
Do You want to add more Recordsy

Enter Bus No105


Enter Bus NameMPSRTC
Enter Number of Passengers60
Enter Bus Fare550
Do You want to add more Recordsn

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

Enter Bus Name to SearchOSRTC


104 OSRTC 40 350.0
Search String Found 1 times

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

Enter Lower range of Passengers40


Enter upper range of Passengers50
102 JSRTC 45 250.0
103 UPSRTC 50 500.0
104 OSRTC 40 350.0
Search String Found 3 times

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

Enter Lower range of Passengers30


Enter upper range of Passengers40
No of lines written to new file is 1

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

Enter Bus Name to ModifyOSRTC


Record to be Modified is 104 OSRTC 40 350.0

Enter New Records


Enter Bus No1044
Enter Bus NnameOSRTCC
Enter Number of Passengers45
Enter Bus Fare365
Record Modified

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

Enter Bus Name to DeleteOSRTC


Record to be Deleted is 1044 OSRTCC 45 365.0

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

Enter Roll Number :1


Enter Name :Amit
Add More ?(Y)y

Enter Roll Number :2


Enter Name :Jasbir
Add More ?(Y)y

Enter Roll Number :3


Enter Name :Vikral
Add More ?(Y)n

Enter Roll number to search :2


## Name is : Jasbir ##
Search more ?(Y) :y

Enter Roll number to search :1


## Name is : Amit ##
Search more ?(Y) :y

Enter Roll number to search :4


####Sorry! Roll number not found ####
Search more ?(Y) :n
#Program to create binary file to store Rollno, Name and Marks and update marks of
entered Rollno

'''
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

Enter Roll Number :2


Enter Name :Vikrant
Enter Marks :88
Add More ?(Y)y

Enter Roll Number :3


Enter Name :Nitin
Enter Marks :66
Add More ?(Y)n

Enter Roll number to update :2


## Name is : Vikrant ##
## Current Marks is : 88 ##
Enter new marks :90
## Record Updated ##
Update more ?(Y) :y

Enter Roll number to update :2


## Name is : Vikrant ##
## Current Marks is : 90 ##
Enter new marks :95 ##
Record Updated ##
Update more ?(Y) :n
import os
import pickle

#Accepting data for Dictionary


def insert_rec_binary():
rollno = int(input('Enter roll number:'))
name = input('Enter Name:')
marks = int(input('Enter Marks'))

#Creating the dictionary


rec = {'Rollno':rollno,'Name':name,'Marks':marks}

#Writing the Dictionary


f = open('student.dat','ab')
pickle.dump(rec,f)
f.close()

#Reading the records


def read_rec_binary():
f = open('student.dat','rb')
while True:
try:
rec = pickle.load(f)
print('Roll Num:',rec['Rollno'])
print('Name:',rec['Name'])
print('Marks:',rec['Marks'])
except EOFError:
break
f.close()

#Searching a record based on Rollno


def search_rec_binary_roll():
f = open('student.dat','rb')
r=int(input("Enter Roll Number to Search"))
flag = False
while True:
try:
rec = pickle.load(f)
if rec['Rollno'] == r:
print('Roll Num:',rec['Rollno'])
print('Name:',rec['Name'])
print('Marks:',rec['Marks'])
flag = True
except EOFError:
break
if flag == False:
print('No Records found')
f.close()

#Searching a record based on Marks Range


def search_rec_binary_marks(lb,ub):
f = open('student.dat','rb')
flag = False
while True:
try:
rec = pickle.load(f)
if rec['Marks']>=lb and rec['Marks']<=ub:
print('Roll Num:',rec['Rollno'])
print('Name:',rec['Name'])
print('Marks:',rec['Marks'])
flag = True
except EOFError:
break
if flag == False:
print('No Records found')
f.close()

#Copy records based on Marks Range


def copy_rec_binary_marks(lb,ub):
f = open('student.dat','rb')
f1= open('student1.dat','ab')
flag = False
while True:
try:
rec = pickle.load(f)
if rec['Marks']>=lb and rec['Marks']<=ub:
pickle.dump(rec,f1)
flag = True
except EOFError:
break
if flag == False:
print('No Records found')
else:
print ('Records Copied Successfully')
f.close()
f1.close()

#Marks Modification for a RollNo


def update_rec_binary(r,m):
f = open('student.dat','rb')
reclst = []
while True:
try:
rec = pickle.load(f)
reclst.append(rec)
except EOFError:
break
f.close()
for i in range (len(reclst)):
if reclst[i]['Rollno']==r:
reclst[i]['Marks'] = m
f = open('student.dat','wb')
for x in reclst:
pickle.dump(x,f)
f.close()

#Deleting a record based on Rollno


def delete_rec_binary(r):
f = open('student.dat','rb')
reclst = []
while True:
try:
rec = pickle.load(f)
reclst.append(rec)
except EOFError:
break
f.close()
f = open('student.dat','wb')
for x in reclst:
if x['Rollno']==r:
continue
pickle.dump(x,f)
f.close()

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

Enter roll number:2


Enter Name:XYZW
Enter Marks65

Enter roll number:3


Enter Name:PQRS
Enter Marks85

Enter roll number:4


Enter Name:MNOP
Enter Marks75

Enter roll number:5


Enter Name:JKLF
Enter Marks80

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

Enter Roll Number to Search4


Roll Num: 4
Name: MNOP
Marks: 75

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

Enter Lower range of Marks70


Enter upper range of Marks80
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 Choice5

Enter Lower range of Marks75


Enter upper range of Marks80
Records Copied Successfully

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

Enter RollNo to Modify2


Enter Marks to Update90

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

NOTE : if the original content of file


India is my country
I love python
Python learning is fun

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

print("Total Vowels in file :",v)


print("Total Consonants in file :",c)
print("Total Capital letters in file :",u)
print("Total Small letters in file :",l)
print("Total Other than letters :",o)

f.close()

'''

NOTE : if the original content of file is:


India is my country
I love python
Python learning is fun
123@

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

Enter Employee Number 1


Enter Employee Name Amit
Enter Employee Salary :90000
## Data Saved... ##
Add More ?y

Enter Employee Number 2


Enter Employee Name Sunil
Enter Employee Salary :80000
## Data Saved... ##
Add More ?y

Enter Employee Number 3


Enter Employee Name Satya
Enter Employee Salary :75000
## Data Saved... ##
Add More ?n

Enter Employee Number to search :2


============================
NAME : Sunil SALARY : 80000
Search More ? (Y)y

Enter Employee Number to search :3


============================
NAME : Satya SALARY : 75000
Search More ? (Y)y

Enter Employee Number to search :4


==========================
EMPNO NOT FOUND
==========================
Search More ? (Y)n
STACK
#Program to implement Stack in Python using List

'''
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

#Program to implement Queue in Python using List

'''

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

#Program 1 : Display all records of EMP table

import mysql.connector

mydb=mysql.connector.connect(host='localhost',
user='root',
password='kvhec',
database='student',
charset='utf8'
)

mycursor=mydb.cursor()

mycursor.execute("SELECT * FROM EMP")

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

mycursor.execute("SELECT * FROM EMP WHERE JOB='CLERK'")


resultset=mycursor.fetchall()
print (resultset)

for rec in resultset:


print (rec)

#for rec in resultset:


#if rec[2]=='CLERK':
#print (rec)
'''

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

jb=input("Enter Job to Display")


sqlstr="SELECT * FROM EMP WHERE JOB='"+jb+"'"
print (sqlstr)

mycursor.execute(sqlstr)
resultset=mycursor.fetchall()
#print (resultset)

for rec in resultset:


print (rec)
'''
'''
#Program 1 : Insert a new record to EMP table
import mysql.connector
mydb=mysql.connector.connect(host='localhost',
user='root',
password='kvhec',
database='student',
charset='utf8'
)
mycursor=mydb.cursor()

mystr="INSERT INTO EMP VALUES(1001,'ABCD','ABCD',1002,'2020-09-


25',2000,NULL,10)"

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

eno=int(input("Enter Employee Number to Change"))

mystr="UPDATE EMP SET SAL=SAL+500 WHERE EMPNO="+str(eno)

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

eno=int(input("Enter Employee Number to Delete"))

mystr="DELETE FROM EMP WHERE EMPNO="+str(eno)

mycursor.execute(mystr)

mydb.commit()
'''
#Program to connect with database and store record of employee and display records.

import mysql.connector as mycon


con = mycon.connect(host='127.0.0.1',user='root',password="admin")
cur = con.cursor()
cur.execute("create database if not exists company")
cur.execute("use company")
cur.execute("create table if not exists employee(empno int, name varchar(20), dept
varchar(20),salary int)")
con.commit()

choice=None
while choice!=0:
print("1. ADD RECORD ")
print("2. DISPLAY RECORD ")
print("0. EXIT")

choice = int(input("Enter Choice :"))


if choice == 1:
e = int(input("Enter Employee Number :"))
n = input("Enter Name :")
d = input("Enter Department :")
s = int(input("Enter Salary :"))
query="insert into employee values({},'{}','{}',{})".format(e,n,d,s)
cur.execute(query)
con.commit()
print("## Data Saved ##")
elif choice == 2:
query="select * from employee"
cur.execute(query)
result = cur.fetchall()
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])
elif choice==0:
con.close()
print("## Bye!! ##")
else:
print("## INVALID CHOICE ##")
OUTPUT

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.

import mysql.connector as mycon


con = mycon.connect(host='127.0.0.1',user='root',password="admin")
cur = con.cursor()
cur.execute("create database if not exists company")
cur.execute("use company")
cur.execute("create table if not exists employee(empno int, name varchar(20), dept
varchar(20),salary int)")
con.commit()

choice=None
while choice!=0:
print("1. ADD RECORD ")
print("2. DISPLAY RECORD ")
print("0. EXIT")

choice = int(input("Enter Choice :"))


if choice == 1:
e = int(input("Enter Employee Number :"))
n = input("Enter Name :")
d = input("Enter Department :")
s = int(input("Enter Salary :"))
query="insert into employee values({},'{}','{}',{})".format(e,n,d,s)
cur.execute(query)
con.commit()
print("## Data Saved ##")
elif choice == 2:
query="select * from employee"
cur.execute(query)
result = cur.fetchall()
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])
elif choice==0:
con.close()
print("## Bye!! ##")
else:
print("## INVALID CHOICE ##")
OUTPUT

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.

import mysql.connector as mycon


con = mycon.connect(host='localhost',user='root',password="admin", database="company")
cur = con.cursor()

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
########################################

ENTER EMPNO TO SEARCH :1


EMPNO NAME DEPARTMENT SALARY
1 AMITSALES 9000
SEARCH MORE (Y) :y

ENTER EMPNO TO SEARCH :2


EMPNO NAME DEPARTMENT SALARY
2 NITIN IT 80000
SEARCH MORE (Y) :y

ENTER EMPNO TO SEARCH :4


Sorry! Empno not found SEARCH MORE (Y) :n
#Program to connect with database and update the employee record of entered empno.

import mysql.connector as mycon


con = mycon.connect(host='localhost',user='root',password="admin", database="company")
cur = con.cursor()
print("#"*40)
print("EMPLOYEE UPDATION FORM")
print("#"*40)
print("\n\n")
ans='y'

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
########################################

ENTER EMPNO TO UPDATE :2


EMPNO NAME DEPARTMENT SALARY
2 NITIN IT 90000

## ARE YOUR SURE TO UPDATE ? (Y) :y


== YOU CAN UPDATE ONLY DEPT AND SALARY ==
== FOR EMPNO AND NAME CONTACT ADMIN ==
ENTER NEW DEPARTMENT,(LEAVE BLANK IF NOT WANT TO CHANGE )
ENTER NEW SALARY,(LEAVE BLANK IF NOT WANT TO CHANGE )
## RECORD UPDATED ##
UPDATE MORE (Y) :y

ENTER EMPNO TO UPDATE :2


EMPNO NAME DEPARTMENT SALARY
2 NITIN IT 90000

## ARE YOUR SURE TO UPDATE ? (Y) :y


== YOU CAN UPDATE ONLY DEPT AND SALARY ==
== FOR EMPNO AND NAME CONTACT ADMIN ==
ENTER NEW DEPARTMENT,(LEAVE BLANK IF NOT WANT TO CHANGE )SALES
ENTER NEW SALARY,(LEAVE BLANK IF NOT WANT TO CHANGE )
## RECORD UPDATED ## UPDATE MORE (Y) :Y

ENTER EMPNO TO UPDATE :2


EMPNO NAME DEPARTMENT SALARY
2 NITIN SALES 90000

## ARE YOUR SURE TO UPDATE ? (Y) :Y


== YOU CAN UPDATE ONLY DEPT AND SALARY ==
== FOR EMPNO AND NAME CONTACT ADMIN ==
ENTER NEW DEPARTMENT,(LEAVE BLANK IF NOT WANT TO CHANGE )
ENTER NEW SALARY,(LEAVE BLANK IF NOT WANT TO CHANGE ) 91000
## RECORD UPDATED ##
UPDATE MORE (Y) :Y

ENTER EMPNO TO UPDATE :2


EMPNO NAME DEPARTMENT SALARY
2 NITIN SALES 91000

## ARE YOUR SURE TO UPDATE ? (Y) :N


UPDATE MORE (Y) :N
#Program to connect with database and delete the record of entered employee number.
import mysql.connector as mycon
con = mycon.connect(host='localhost',user='root',password="admin", database="company")
cur = con.cursor()
print("#"*40)
print("EMPLOYEE DELETION FORM")
print("#"*40)
print("\n\n")
ans='y'

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
########################################

ENTER EMPNO TO DELETE :2


EMPNO NAME DEPARTMENT SALARY
2 NITIN SALES 91000

## ARE YOUR SURE TO DELETE ? (Y) :y


=== RECORD DELETED SUCCESSFULLY! ===
DELETE MORE ? (Y) :y

ENTER EMPNO TO DELETE :2


Sorry! Empno not found DELETE MORE ? (Y) :n
MISCELLANEOUS

Program 1: Program to generate random number 1-6, simulating a dice

import random
import time

print ("Press CTRL+C to stop the dice”)


play='y'

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

print("==== Welcome To Stick Picking Game :: Computer Vs User =====")


print("Rule: 1) Both User and Computer can pick sticks between 1 to 4 at a time")
print(" 2) Whosoever picks the last stick will be the looser")
print("==== Lets Begin ======")

playerName = input("Enter Your Name :")


userPick=0
PrintStick(TotalStick)

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

==== Welcome To Stick Picking Game :: Computer Vs User =====


Rule:
1) Both User and Computer can pick sticks between 1 to 4 at a time
2) Whosoever picks the last stick will be the looser
==== Lets Begin ======
Enter Your Name :RAJ
ooooooooooooooooooooo
|||||||||||||||||||||
|||||||||||||||||||||
|||||||||||||||||||||
|||||||||||||||||||||
You Can Pick stick between 1 to 4
RAJ: Enter Number of Stick to Pick3
oooooooooooooooooo
||||||||||||||||||
||||||||||||||||||
||||||||||||||||||
||||||||||||||||||
************************************************************
Press any key...
Computer Picks : 2 Sticks
oooooooooooooooo
||||||||||||||||
||||||||||||||||
||||||||||||||||
||||||||||||||||
************************************************************
Press any key...
You Can Pick stick between 1 to 4
RAJ: Enter Number of Stick to Pick4
oooooooooooo
||||||||||||
||||||||||||
||||||||||||
||||||||||||
************************************************************
Press any key...
Computer Picks : 1 Sticks
ooooooooooo
|||||||||||
|||||||||||
|||||||||||
|||||||||||
************************************************************
Press any key...
You Can Pick stick between 1 to 4
RAJ: Enter Number of Stick to Pick2
ooooooooo
|||||||||
|||||||||
|||||||||
|||||||||
************************************************************
Press any key...
Computer Picks : 3 Sticks
oooooo
||||||
||||||
||||||
||||||
************************************************************
Press any key...
You Can Pick stick between 1 to 4
RAJ: Enter Number of Stick to Pick3
ooo
|||
|||
|||
|||
************************************************************
Press any key...
Computer Picks : 2 Sticks
o
|
|
|
|
## WINNER : COMPUTER ##
************************************************************
Press any key...
COMPUTER NETWORK
Computer Network:
A group of two or more similar things or people interconnected with each other is called network.

STRUCTURE OF THE INTERNET

NETWORK DEVICES

MODEM

RJ-45 (REGISTERED JACK - 45)


NIU – NETWORK INTERFACE UNIT or NIC – NETWORK INTERFACE CARD or LAN
CARD or ETHERNET CARD

HUB

SWITCH

REPEATER
BRIDGE

ROUTER

GATEWAY

WiFi CARD
MESH TOPOLOGY

RING TOPOLOGY

BUS TOPOLOGY
STAR TOPOLOGY

TRANSMISSION MEDIA

UTP

COAXIAL CABLE

OPTICAL CABLE FIBRE (OFC)


KENDRIYA VIDYALAYA NO 1 HEC, RANCHI

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)

TO BE CARRIED OUT ON TABLE EMPNEW


INSERT
i) Write the commands to insert the first two records in the table EMP
UPDATE
i) Change the Department of FORD to 10
ii) Increase the SALARY of all Employees by 5 %
iii) Input the COMM of BLAKE 10% of SALARY
DELETE
i) Delete the record of BLAKE
ii) Delete the record of all employees who are in Deptno 10
ALTER
i) Add a new column Phone char(10) to the table EMP
ii) Increase the column size of ENAME by 10
iii) Drop the column Phone char(10) from the table EMP
DROP
i) Drop the table EMPNEW

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;

iv) SELECT * FROM EMP WHERE SAL<=1000 AND SAL>=1200;


v) SELECT * FROM EMP WHERE HIREDATE>=‘1981-01-01’ AND HIREDATE<=’ 1981-12-31’;

vi) SELECT * FROM EMP WHERE JOB=’SALESMAN’ OR JOB=’MANAGER’;


vii) SELECT * FROM EMP WHERE DEPTNO=10 OR DEPTNO=20;

> < BETWEEN


i) SELECT * FROM EMP WHERE SAL BETWEEN 800 AND 1500;
ii) SELECT * FROM EMP WHERE HIREDATE BETWEEN ‘1980-01-01’ AND 1981-01-01’;
iii) SELECT * FROM EMP WHERE COMM BETWEEN 0 AND 200;

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

You might also like