0% found this document useful (0 votes)
24 views

Programs for practical file for app

Uploaded by

shin87411
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)
24 views

Programs for practical file for app

Uploaded by

shin87411
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/ 47

# Write a python program to check the given number is prime or not.

a=int(input("Enter a number : "))


half=a/2
i=2
ctr=0

print ("The factors of ",a,"are :")

while i<=half:
if a%i==0:
print ("It's Not a prime number")
break
i=i+1

if i>half:
print ("\nIt is a prime number")

Run Part :-

Enter a number : 7
The factors of 7 are :

It is a prime number
'''Write a Python Program to Count the Occurrences of a Word (whole word) in a string using user
defined function.
'''

def countword(string,s):
k=0
words = f.split()

print(f)
print(words)

for i in words:
if(i==s):
k=k+1
print("Occurrences of the word:")
print(k)

#__main__

f="this is is a book"
search ="is"
countword(f,search)

Run Part:-
this is is a book
['this', 'is', 'is', 'a', 'book']
Occurrences of the word:
2
#Write a Python program to show the frequency of each element in list.
'''
L1=[]
n=int(input("enter the number of elements ="))
for i in range(n):
item = int(input('Enter No. ='))
L1.append(item)
'''
L1=[11,2,2,1,3,11,4]
print("the elementsin List L1",L1)
L2=L1
L2.sort()
print("the elementsin List L2",L2)

d=dict()
for ch in L2:
if ch in d:
d[ch]+=1
else:
d[ch]=1

for i in d:
print (i, d[i])

Run Part :-
the elementsin List L1 [11, 2, 2, 1, 3, 11, 4]
the elementsin List L2 [1, 2, 2, 3, 4, 11, 11]
11
22
31
41
11 2
#Write a Python program to search an element in a list and display the frequency of element present in
list and their location.

'''
L1=[]
n=int(input("enter the number of elements ="))
for i in range(n):
item = int(input('Enter No. ='))
L1.append(item)
'''

L1=[3,11,2,2,1,3,11,3,3]
print("the elements in List L1",L1)
# searched element
x=3
#count the frequency of x
d=dict()
d[x]=0
for ch in L1:
if x==int(ch):
d[x]+=1
print("Frequency of x in list:=",d.values())
v=d[x]
print(v)

#find the location of x in list


L2=[]
d=dict()
d[x]=0
count=1
for ch in L1:
if x==int(ch):
L2.append(count)
count+=1
print("Location of x in List :=", L2)

dict1=dict()
dict1.update({x:[v, L2]})
print("Location of x in List :=", dict1)

Run part:-
the elements in List L1 [3, 11, 2, 2, 1, 3, 11, 3, 3]
Frequency of x in list:= dict_values([4])
4
Location of x in List := [1, 6, 8, 9]
Location of x in List := {3: [4, [1, 6, 8, 9]]}
# Write a python program to pass a list to a function and double the odd values and half even values of
a list and display list element after changing.
def listprocess(L1):
length=len(L1)
print(length)
for i in range(0,length):
if(i%2==0):
L1[i]=L1[i]*2
else:
L1[i]=L1[i]/2
return(L1)

#__main__
'''
L1=[]
n=int(input("enter the number of elements ="))
for i in range(n):
item = int(input('Enter No. ='))
L1.append(item)
'''
L1=[1,2,3,4,5,6]

print("the elements in List L1",L1)


L=listprocess(L1)
print(L)

Run part:-
the elements in List L1 [1, 2, 3, 4, 5, 6]
6
[2, 1.0, 6, 2.0, 10, 3.0]
# Write a python program to input n numbers in tuple and pass it to a function to count how many even
and odd numbers are entered.
def counter(T):
length=len(T)
print("Length of tuple is :-", length)
counteven=0
countodd=0
for i in range(0,length):
if T[i]%2==0:
counteven+=1
else:
countodd+=1
print("\nTotal even numbers are :=", counteven)
print("Total odd numbers are :=",countodd)

#__main__
# creation of tuple using list
L1=[]
n=int(input('ENTER THE NUMBER OF ELEMENTS :'))
for i in range(n):
print('Enter ', i+1 , ' element= ',end=' ')
element = int(input())
L1.append(element)

print("The list 1 is : ",L1)


T1=tuple(L1)
# creation of tuple from list
T1=tuple(L1) # ONLY ONE ARGUMENT
print("\nThe tuple is : ",T1)
counter(T1)
Run Part:-
ENTER THE NUMBER OF ELEMENTS :5
Enter 1 element= 1
Enter 2 element= 2
Enter 3 element= 3
Enter 4 element= 7
Enter 5 element= 8
The list 1 is : [1, 2, 3, 7, 8]

The tuple is : (1, 2, 3, 7, 8)


Length of tuple is :- 5

Total even numbers are := 2


Total odd numbers are := 3
#Write a python program to create a function for a dictionary with key & value and update value of that
key in dictionary entered by user.
def changevalue(sm):
x=int(input("Enter the key:="))
name=input("Enter new name:=")
age= int(input("Enter new age:="))
for k in sm.keys():
if(k==x):
sm.update({k:[name,age]})
print('PRINTING WHOLE DICTIONARY IN FUNCTION\n',sm)

#__main__
'''
#DECLARATION OF A BLANK DICTIONARY
studentmark= {}
#input in run time
n=int(input('ENTER THE NUMBER OF ELEMENTS\t :'))
for i in range(n):
print('\nEnter ', i+1 , ' element= ',end='\n')
rollno= int(input("Enter the Rollno\t:"))
name = input('Enter the name\t:')
age = input('Enter the age\t:')
studentmark[rollno]=[name,age]
'''

studentmark={100:['ram','10'], 200:['laxman,20']}
# PRINTING WHOLE DICTIONARY
print('PRINTING WHOLE DICTIONARY\n',studentmark)
# find the length using len()
length=len(studentmark)
print('\nfind the length using len() =' , length)

changevalue(studentmark)
print('PRINTING WHOLE DICTIONARY\n',studentmark)

Run Part:-
PRINTING WHOLE DICTIONARY
{100: ['ram', '10'], 200: ['laxman,20']}

find the length using len() = 2


Enter the key:=200
Enter new name:=vijay
Enter new age:=25
PRINTING WHOLE DICTIONARY IN FUNCTION
{100: ['ram', '10'], 200: ['vijay', 25]}
PRINTING WHOLE DICTIONARY
{100: ['ram', '10'], 200: ['vijay', 25]}
'''Write a python promgram which counts vowels in a string using user defined function.
For example :-
For given input string - this is a book
The output should be - 5 '''
def countvowel(s):
vow="aeiouAEIOU"
ctr=0
for ch in s:
if ch in vow:
ctr=ctr+1
print ("The total vowels are :",ctr)

def countallvowel(s):
ctr=0
for i in s:
if (i=='A' or i=='a' or i=='E' or i=='e' or i=='I'or i=='i' or i=='O' or i=='o' or i=='U'or i=='u'):
ctr=ctr+1
return ctr

#__main__
#s=input("Enter the string")
s="this is a book"

print("The given string is\n",s)


countvowel(s)

x=countallvowel(s)
print ("The total vowels are :",x)
Run Part:-
The given string is
this is a book
The total vowels are : 5
The total vowels are : 5
# Write a program in python to generate random numbers between 1 and 6.

import random

print("random number between 1 and 6")

print("\nrandint(a,b) return a random integer between a and b")

print(random.randint(1,6)) # we may get 1 and 6 also

Run Part:-
random number between 1 and 6

randint(a,b) return a random integer between a and b


5
# Write a program in python to explain mathematical functions-len-pow-str-int-float-range-type-abs-
divmod-sum.
st="this"
print("the length of st is :=", len(st))

x=pow(2,3) #1
print(x)

a=123.45
STR=str(a)
print(STR)

b=float(STR) #2
print(b)

c=int('15') #3
print(c)

print(range(5))

print(type(c))

d=-15
print("absolute value :=", abs(d)) #4

print("quotient and remainder:=" ,divmod(9,5)) # return quotient and remainder #5

print(sum([1,2,3]))
print(sum((1,2,3)))
print(sum([1,2,3],5))
Run part:-
the length of st is := 4
8
123.45
123.45
15
range(0, 5)
<class 'int'>
absolute value := 15
quotient and remainder:= (1, 4)
6
6
11
# Write a program in python to explain mathematical functions-max-min-oct-hex-round.

print("max")
print(max([5,7,6],[2,3,4])) # match first element only of both lists
print(max([5,7,6],[7,4,3]))
print(max((5,7,6),(2,3,4))) # match first element only of both tuples

print("min")
print(min([5,7,6],[2,3,4])) # match first element only of both lists
print(min([5,7,6],[7,4,3]))
print(min((5,7,6),(2,3,4))) # match first element only of both tuples

print(oct(10))

print(hex(10))
print(hex(15))

x=7.5550
y=int(x)
print(y)

z=round(x)
print(z)

p=round(x,2)
print(p)
Run part:-
max
[5, 7, 6]
[7, 4, 3]
(5, 7, 6)
min
[2, 3, 4]
[5, 7, 6]
(2, 3, 4)
0o12
0xa
0xf
7
8
7.55
# Write a program in python to explain string functions-join-split-replace.

#join only joins strings


st1="#"
print(st1.join("Student")) # joind string

st2="##"
print(st2.join("Student"))

st3="##"
print(st3.join(["good", "morning", "all"])) # join with list

st4="##"
print(st3.join(("good", "morning"))) # join with tuple

#st4="##"
#print(st3.join((777, "good", "morning"))) # show errors- only string allowed in tuple

#split makes list


st5="this is a book"
print(st5.split()) # split at spces in list form

st6="this is a ice-cream"
print(st6.split("i")) # split at 'i'

#replace
st7="this is a book"
print(st7.replace('is','are')) #find and replace

#capitalize
st8="this is a book"
print(st8.capitalize()) # capital first letter of a string
Run part:-
S#t#u#d#e#n#t
S##t##u##d##e##n##t
good##morning##all
good##morning
['this', 'is', 'a', 'book']
['th', 's ', 's a ', 'ce-cream']
thare are a book
This is a book
# Write a program in python to explain string constant function.

import string

print("print all alphabet in lowercase and uppercase")


print(string.ascii_letters)

print("\nprint all alphabet in lowercase")


print(string.ascii_lowercase)

print("\nprint all alphabet in uppercase")


print(string.ascii_uppercase)

print("\nprint all digits")


print(string.digits)

print("\nprint all hexadecimal")


print(string.hexdigits)

print("\nprint all octal")


print(string.octdigits)

print("\nprint all punctuation")


print(string.punctuation)

st1="this is a book"
print("\nmake each word of a string capital")
print(string.capwords(st1)) # capwords()= split()+capitalize()+join()
Run part:-
print all alphabet in lowercase and uppercase
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ

print all alphabet in lowercase


abcdefghijklmnopqrstuvwxyz

print all alphabet in uppercase


ABCDEFGHIJKLMNOPQRSTUVWXYZ

print all digits


0123456789

print all hexadecimal


0123456789abcdefABCDEF

print all octal


01234567

print all punctuation


!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~

make each word of a string capital


This Is A Book
# Write a program in python to make a user defined module for an arithmetic calculator.
Cal.py file
def calculator(x,y,ch):
if(ch=='+'):
c=a+b
elif(ch=='-'):
c=a-b
elif(ch=='*'):
c=a*b
elif(ch=='/'): # float quotient
c=a/b
elif(ch=='//'): #integer quotient
c=a//b
elif(ch=='%'): # remainder
c=a%b
return c

our main file :-


import cal
#__main__
a=9
b=2
x=calculator(a,b,'%')
print(x)

Run part:-
1
# Write a program in python to read a text line by line and display each word separated by #.
# make one.txt file on drive and give path in below line.
myfilein = open('one.txt','r')
str=' ' # must have ateast one space or one character or any thing

while str:
str= myfilein.readline()
words = str.split()
for i in words:
print (i,"#",end='')
print()

myfilein.close()

content of one.text file:-


hello students
this is a book
that is my book
this is mobile

Run part:-
hello #students #
this #is #a #book #
that #is #my #book #
this #is #mobile #
#Write a python program to copy all the lines excepts the lines which contain the character 'a' from a
file named "article.txt" to another file named "copy.txt".
myfilein = open('article.txt','r')
myfileout = open('copy.txt','w')

str=' ' # must have ateast one space

while str:
str= myfilein.readline()
if 'a' not in str:
print(str,end='')
myfileout.write(str)
myfilein.close()
myfileout.close()

Contents of article.txt file:-


hello students
this is a book
that is my book
this is mobile

Run part:-
hello students
this is mobile

Contents of copy.txt file:-


hello students
this is mobile
# Write a python program to read characters from keyboard one by one, then store all lowercase letters
inside a file "LOWER", all uppercase letters gets inside a file "UPPER" and other characters inside file
"OTHERS".

myfile1 = open('LOWER.txt','w')
myfile2 = open('UPPER.txt','w')
myfile3 = open('OTHERS.txt','w')

Llower=[] # creation of blank list


Lupper=[]
Lothers=[]

str= input("Enter the contents:=")


for ch in str:
if ch >= 'a' and ch <='z':
Llower.append(ch)
elif ch >='A' and ch<='Z':
Lupper.append(ch)
else:
Lothers.append(ch)

print("Contents in LOWER FILE:-", Llower)


print("Contents in UPPER FILE:-",Lupper)
print("Contents in OTHER FILE:-",Lothers)

myfile1.writelines(Llower)
myfile2.writelines(Lupper)
myfile3.writelines(Lothers)

myfile1.close()
myfile2.close()
myfile3.close()

Run part:-
Enter the contents:=These are 10 apples.
Contents in LOWER FILE:- ['h', 'e', 's', 'e', 'a', 'r', 'e', 'a', 'p', 'p', 'l', 'e', 's']
Contents in UPPER FILE:- ['T']
Contents in OTHER FILE:- [' ', ' ', '1', '0', ' ', '.']
#Write a program in python to create a binary file with rollno and name. Search for a given roll number
and display name, if not found display appropriate message.
import pickle
#class declaration
class student:
def __init__(self, rno = 0 , nm = "" ):
self.rollno=rno
self.name=nm

def getdetails(self):
print("Enter the details\n")
self.rollno=input("Enter the rollno.:=")
self.name=input("Enter the name:=")

def show(self):
print("\n\nReport of students are:\n")
print("The Roll Number of student is: ", self.rollno)
print("The name of student is : ", self.name)

def getrollno(self):
return int(self.rollno)

# object creation
object1= student(1,"ram")
object1.show()

object2= student()
object2.getdetails()
object2.show()
#Writing object1 on binary file.
myfile = open("Student.log","wb")
pickle.dump(object1,myfile) # writing the dictionary in student.log file.
# dump() having two arguments.
pickle.dump(object2,myfile)
myfile.close()

# reopen the binary file in read mode


myfile = open("Student.log","rb")
r=int(input("Enter the rollno to be searached"))
flag=0
try:
while True:
object3=pickle.load(myfile) # load() raise EOF error when it reaches end of file.
y = object3.getrollno()
if(r==y):
object3.show()
flag=1
except EOFError:
if(flag==0):
print("record not found")
myfile.close()

Run part:- ( the record of one student is taken in compile time and second one is taken in run time. )
Report of students are:
The Roll Number of student is: 1
The name of student is : ram
Enter the details
Enter the rollno.:=2
Enter the name:=laxman

Report of students are:

The Roll Number of student is: 2


The name of student is : laxman

Enter the rollno to be searached1

Report of students are:


The Roll Number of student is: 1
The name of student is : ram
#Write a python program to create a binary file with rollno, name and marks, input a rollno and update
the marks.
import pickle
#class declaration
class student:
def __init__(self, rno = 0 , nm = "" ):
self.rollno=rno
self.name=nm
self.m1,self.m2,self.m3,self.m4,self.m5=90.0,80.0,70.0,60.0,50.0

def getmark(self):
print("Enter the marks:=\n")
self.m1=float(input("Enter marks for Computer Science:="))
self.m2=float(input("Enter marks for Math:="))
self.m3=float(input("Enter marks for Physics:="))
self.m4=float(input("Enter marks for chemistry:="))
self.m5=float(input("Enter marks for English:="))

def show(self):
print("Report of students are:\n")
print("The Roll Number of student is: ", self.rollno)
print("The name of student is : ", self.name)
print("the marks:=\n")
print("marks for Computer Science:=",self.m1)
print("marks for Math :=",self.m2)
print("marks for Physics :=",self.m3)
print("marks for chemistry :=",self.m4)
print("marks for English :=",self.m5)
def returnrno(self):
return int(self.rollno)
# object creation
object1= student(1,"ram")
#object1.getmark()
object1.show()
object2= student(2,"laxman")
#object2.getmark()
object2.show()

# creating binary file


myfile = open("Student.log","wb")
pickle.dump(object1,myfile) # writing the dictionary in student.log file.
pickle.dump(object2,myfile) # dump() having two arguments.
myfile.close()

#update new binary file


filein = open("Student.log","rb")
fileout = open("newStudent.log","wb")
x=int(input("Enter the rollno need to be updated marks:="))
try:
while True:
object=pickle.load(filein)
if object.returnrno()==x:
object.getmark()
pickle.dump(object,fileout)
except EOFError:
filein.close()
fileout.close()
# copy the data in old file
filein = open("newStudent.log","rb")
fileout = open("Student.log","wb")

try:
while True:
object=pickle.load(filein)
pickle.dump(object,fileout)
except EOFError:
filein.close()
fileout.close()

# open main file in read mode


print("\nShowing the data with updated value\n")
filein = open("Student.log","rb")
try:
while True:
object=pickle.load(filein)
object.show()
except EOFError:
filein.close()

Run part:-
Report of students are:

The Roll Number of student is: 1


The name of student is : ram
the marks:=
marks for Computer Science:= 90.0
marks for Math := 80.0
marks for Physics := 70.0
marks for chemistry := 60.0
marks for English := 50.0
Report of students are:

The Roll Number of student is: 2


The name of student is : laxman
the marks:=

marks for Computer Science:= 90.0


marks for Math := 80.0
marks for Physics := 70.0
marks for chemistry := 60.0
marks for English := 50.0
Enter the rollno need to be updated marks:=2
Enter the marks:=

Enter marks for Computer Science:=98


Enter marks for Math:=78
Enter marks for Physics:=87
Enter marks for chemistry:=79
Enter marks for English:=87

Showing the data with updated value

Report of students are:

The Roll Number of student is: 1


The name of student is : ram
the marks:=

marks for Computer Science:= 90.0


marks for Math := 80.0
marks for Physics := 70.0
marks for chemistry := 60.0
marks for English := 50.0
Report of students are:
The Roll Number of student is: 2
The name of student is : laxman
the marks:=

marks for Computer Science:= 98.0


marks for Math := 78.0
marks for Physics := 87.0
marks for chemistry := 79.0
marks for English := 87.0
#Write a python program to create a csv file with empid, name and mobile no and search empid, update
the record and display on screen.
import csv
# create a csv file
dict1= {}
dict1= {1: ['kamal', 9999912345] , 2:[ 'ram', 8888812345] }
with open('data.csv','w') as wfile:
wrt=csv.writer(wfile)
for key,value in dict1.items():
wrt.writerow([key,value])
wfile.close()

# copy csv file in another csv file with update value


rfile = open('data.csv', 'r')
wfile = open('newdata.csv', 'w')
reader =csv.reader(rfile)
writer = csv.writer(wfile)
x=int(input("Enter the code need to be updated:="))
for row in reader:
if int(row[0])==x:
name=input("Enter New Name:=")
mobile=int(input("Enter new mobile no:="))
row[1]=[name,mobile]
writer.writerow(row)
else:
writer.writerow(row)

rfile.close()
wfile.close()
# copy the data in old file
rfile = open('newdata.csv', 'r')
wfile = open('data.csv', 'w')

reader =csv.reader(rfile)
writer = csv.writer(wfile)
for row in reader:
writer.writerow(row)
rfile.close()
wfile.close()

#show the data of with updated value


rfile = open('data.csv', 'r')
reader =csv.reader(rfile)
for row in reader:
print(row)
rfile.close()

Run part:-
Enter the code need to be updated:=2
Enter New Name:=vishnu
Enter new mobile no:=7777712345
['1', "['kamal', 9999912345]"]
['2', "['vishnu', 7777712345]"]
#Write a program in python to explain push, pop,, show & peek concept of a stack.
def push(stk,item):
stk.append(item)
top=len(stk)-1 # update top variable

def POP(stk):
if isEmpty(stk):
return "underflow-stack"
else:
element = stk.pop()
if len (stk) ==0:
top=None
else:
top= len(stk)-1
return element

def SHOWSTACK(stk):
if isEmpty(stk):
print ("STACK IS EMPTY")
else:
top=len(stk)-1
print(stk[top],"<-this is top element")
for a in range(top-1,-1,-1):
print(stk[a])

def peek(stk):
if isEmpty(stk):
return "underflow-stack"
else:
top=len(stk)-1
return stk[top]

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

# __main__

stack = [] # implementation of stack using list


top = None

while True:
print("Enter your Choice in stack:\n")
print("1. Push")
print("2. POP")
print("3. peek")
print("4. Show-stack")
print("5. Exit")
choice= int(input("Enter your choice ( from 1 to 5 ) :"))
if choice ==1 :
item = int(input("Enter the item: "))
push(stack,item)
elif choice==2:
item = POP(stack)
if item == "underflow-stack":
print("The stack is underflow (empty) ")
else:
print("The popped element is : ", item)
elif choice == 3:
item = peek(stack)
if item == "underflow-stack":
print("The stack is underflow (empty) ")
else:
print("The TOP element is : ", item)
elif choice == 4:
SHOWSTACK(stack)
elif choice == 5:
break
else:
print("Invalid choice, please enter from 1 to 5 only")
Run part:-
Enter your Choice in stack:

1. Push
2. POP
3. peek
4. Show-stack
5. Exit
Enter your choice ( from 1 to 5 ) :1
Enter the item: 100
Enter your Choice in stack:

1. Push
2. POP
3. peek
4. Show-stack
5. Exit
Enter your choice ( from 1 to 5 ) :1
Enter the item: 200
Enter your Choice in stack:

1. Push
2. POP
3. peek
4. Show-stack
5. Exit
Enter your choice ( from 1 to 5 ) :1
Enter the item: 300
Enter your Choice in stack:

1. Push
2. POP
3. peek
4. Show-stack
5. Exit
Enter your choice ( from 1 to 5 ) :4
300 <-this is top element
200
100
Enter your Choice in stack:

1. Push
2. POP
3. peek
4. Show-stack
5. Exit
Enter your choice ( from 1 to 5 ) :2
The popped element is : 300
Enter your Choice in stack:

1. Push
2. POP
3. peek
4. Show-stack
5. Exit
Enter your choice ( from 1 to 5 ) :2
The popped element is : 200
Enter your Choice in stack:

1. Push
2. POP
3. peek
4. Show-stack
5. Exit
Enter your choice ( from 1 to 5 ) :2
The popped element is : 100
Enter your Choice in stack:

1. Push
2. POP
3. peek
4. Show-stack
5. Exit
Enter your choice ( from 1 to 5 ) :2
The stack is underflow (empty)
Enter your Choice in stack:

1. Push
2. POP
3. peek
4. Show-stack
5. Exit
Enter your choice ( from 1 to 5 ) :5

>>>
# Write a program in python to take 10 sample phishing email ( in a list or from a text file ) and find the
most common word occuring. ( hint : use dictionary to count number of occurances of each word).
# Write a program in python to take 10 sample phishing email ( in a list or from a text file ) and find the
most common word occuring. ( hint : use dictionary to count number of occurances of each word).
'''
Input : [1, 1, 1, 5, 5, 3, 1, 3, 3, 1,
4, 4, 4, 2, 2, 2, 2]
Output : 1 : 5
2:4
3:3
4:3
5:2
Explanation : Here 1 occurs 5 times, 2
occurs 4 times and so on...
'''
'''
Output:
1: 5
2: 4
3: 3
4: 3
5: 2
'''
# Python program to count the frequency of
# elements in a list using a dictionary

def CountFrequency(my_list):

# Creating an empty dictionary


freq = {}
for item in my_list:
if (item in freq):
freq[item] += 1
else:
freq[item] = 1

for key, value in freq.items():


print ("% s : % s"%(key, value))
#print ("% d : % d"%(key, value))
# Driver function
if __name__ == "__main__":
my_list =['this', 'is', 'that', 'is','book', 'pencil']#we can take mail id here.
#my_list =[1, 1, 1, 5, 5, 3, 1, 3, 3, 1, 4, 4, 4, 2, 2, 2, 2]

CountFrequency(my_list)

Run part:-
this : 1
is : 2
that : 1
book : 1
pencil : 1
#Write a program in python to make connectivity between mysql and python (creation of database &
table) and insert a record.
# first time creation of database and table
# enter and show one row in table
import mysql.connector as c
db=c.connect(host='localhost',user='root', passwd='root')
cur = db.cursor()
cur.execute("show databases")
print(cur)
for i in cur:
print(i)

cur.execute("create database school")


print("\nnew database is created")
cur.execute("show databases")
print(cur)
for i in cur:
print(i)

cur.execute("use school")
cur.execute("create table student(rn int, name char(15), per int)")
cur.execute("describe student")
print("\nthe structure of table student is:")
for i in cur:
print(i)

print("\nEnter the values for student table:")


r = int(input("enter the rollno:="))
n = input("enter the name:=")
p = int(input("enter the percentage"))
#val = (1,"ram",92)
val=(r,n,p)
sql="insert into student values(%s,%s,%s)"
cur.execute(sql,val)
db.commit()
print("sucess")

cur.execute("select * from student")


for i in cur:
print (i)
#Write a program in python to make connectivity between mysql and python (database & table already
created) and insert a record.
#input and show data from an already created table in sql
import mysql.connector as c
db=c.connect(host='localhost',user='root', passwd='root',database='school')
print(db)
cur = db.cursor()
#cur.execute("show databases")
#val = (1,'ram',92)
sql="insert into student values(%s,%s,%s, %s)"
r=int(input("enter roll no::"))
n=input("Enter name::")
p=int(input("Enter %"))
city=input("Enter city:")
val=(r,n,p,city)
cur.execute(sql,val)
db.commit()
print("sucess")

cur.execute("select * from student")


for i in cur:
print (i)
#Write a program in python to make connectivity between mysql and python (database & table already
created) and delete a record.
#input and show data from an already created table in sql
import mysql.connector as c
db=c.connect(host='localhost',user='root', passwd='admin',database='school')
print(db)
cur = db.cursor()

cur.execute("select * from student")


for i in cur:
print (i)

print("\nEnter the rollno to be deleted :")


r = int(input("enter the rollno:="))

sql="delete from student where rn = %s " %(r,)


cur.execute(sql)
db.commit()
print("sucess")

cur.execute("select * from student")


for i in cur:
print (i)
#Write a program in python to make connectivity between mysql and python (database & table already
created) and update a record.
#input and show data from an already created table in sql
import mysql.connector as c
db=c.connect(host='localhost',user='root', passwd='admin',database='school')
print(db)
cur = db.cursor()

cur.execute("select * from student")


for i in cur:
print (i)

print("\nEnter the rollno to be updated :")


r = int(input("enter the rollno:="))

sql="select * from student where rn = %s " %(r,)


cur.execute(sql)
for i in cur:
print (i)

print("\nEnter the values for student table:")


n = input("enter the name:=")
val=(n,r)
sql="update student set name = %s where rn = %s"
cur.execute(sql,val)
db.commit()
print("sucess")

cur.execute("select * from student")


for i in cur:
print (i)

You might also like