Programs for practical file for app
Programs for practical file for app
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)
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]
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)
#__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']}
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"
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
Run Part:-
random number between 1 and 6
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(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.
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
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
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
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()
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')
while str:
str= myfilein.readline()
if 'a' not in str:
print(str,end='')
myfileout.write(str)
myfilein.close()
myfileout.close()
Run part:-
hello students
this is mobile
myfile1 = open('LOWER.txt','w')
myfile2 = open('UPPER.txt','w')
myfile3 = open('OTHERS.txt','w')
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()
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
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()
try:
while True:
object=pickle.load(filein)
pickle.dump(object,fileout)
except EOFError:
filein.close()
fileout.close()
Run part:-
Report of students are:
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()
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__
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):
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("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)