0% found this document useful (0 votes)
0 views37 pages

Computer Practical 2021

This document is a practical report on Python programs, including various tasks such as checking for prime numbers, generating Fibonacci series, and performing operations on strings and lists. It also covers Python-MySQL connectivity for database operations. The report includes a detailed index of programs along with their implementation and examples.

Uploaded by

pawisa2161
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)
0 views37 pages

Computer Practical 2021

This document is a practical report on Python programs, including various tasks such as checking for prime numbers, generating Fibonacci series, and performing operations on strings and lists. It also covers Python-MySQL connectivity for database operations. The report includes a detailed index of programs along with their implementation and examples.

Uploaded by

pawisa2161
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/ 37

COMPUTER SCIENCE

PRACTICAL REPORT FILE


ON
PYTHON PROGRAMS ( INCLUDING
INTERFACE WITH MYSQL )

SESSION : 2020 – 2021

Submitted by: Submitted to:


Yatendra Bajpai Ms. Sarita Gupta
Class : XII
Roll No
INDEX
S.N. Name of Practical Date Sign
1 WAP to input a number and check whether it is a prime
number or not using a user defined fn() 16.04.2020
2 WAP To print fibonacci series upto n terms using a user 23.04.2020
defined fn fib()
3 Program to perform logical operations on string using user 30.04.2020
defined functions
4 Program to perform given operations on input 08.05.2020
String/sentence using user defined functions
5 Program to show various logical operation on List 15.05.2020
6 Write a function Div3and5() that takes a 10 elements numeric 10.07.2020
tuple and return the sum of elements which are divisible by 3
and 5
7 Program to implement all methods/ functions of Dictionary. 17.07.2020
8 Program to store SRNO as key and NAME, TOTAL_MARKS as 24.07.2020
values of n students in a Dictionary and perform following:
(i) Print name, marks in descending order of marks
(ii) Print SRNO, NAME and TOTAL_MARKS of students whose
name begins with 'A'
9 To create a text file “story.txt” with few lines of text. Read the 07.08.2020
file and print its contents along with number of vowels
present in it
10 Program to perform various given operations on a text file. 14.08.2020
11 Program to implement all operation on a binary file 21.08.2020
12 Program to write Train details on a binary file and then 28.08.2020
display details of Trains running from ‘LUCKNOW’ to ‘JAIPUR’
from the file.
13 Program to add records in a binary file "emp.dat", store 04.09.2020
sorted records in another file “sorted.dat” and display all
sorted records.
14 Program to add details and search a particular record in a csv 11.09.2020
file
Program to read and copy records of a csv file matching a 18.09.2020
15 given criterion on another file.
Program to demonstrate all operations on a stack implemented 09.10.2020
16 as a list.
Python – MYSQL Connectivity ( To Insert, Display, Search, 16.10.2020
17 Modify, Delete records in a Table created in a MySQL
database )
Python – MYSQL Connectivity: to display all records where 23.10.2020
18 student name ends with a given char from a SQL database
19 Python –MYSQL Connectivity : to display following 23.10.2020
information from the student table:
i) minimum and maximum fee amount
ii) total fee amount iii) average of fee
Python – MYSQL Connectivity : to add a field in stud table 30.10.2020
20 existing in student database, Fill the new column with 0 if
datatype is int and "X" if datatype is char and Display the
entire content from the table.
Program : 1

# To input a number and check whether it is prime number or not using a


# user defined fn isprime() which returns 1 if the number is prime else 0

def isprime(n):
c=1
for i in range(2,n):
if n%i==0:
c=0
if c==1:
return 1
else:
return 0
n=int(input(“Enter any number”))
if isprime(n):
print("Number is prime")
else:
print("Number is not prime")

Enter the number 29


Number is prime

# Program : 2

# To print fibonacci series upto n terms using a user defined fn fib()

def fib(n):
a,b = -1,1
for i in range(n):
print(a+b,end=" ")
a,b = b, a+b
n=int(input("Enter the number of terms in Fibonacci series ”))
fib(n)

Enter the number of terms in fibonacci series 10


0 1 1 2 3 5 8 13 21 34
# Program : 3
# Program to perform logical operations on string using user defined functions

def count(St):
c=0
for i in St:
if i == ' ':
c=c+1
return c

def count1(St):
v=c=d=s=0
for i in range(len(St)):
if St[i].isalpha():
if St[i] in "aeiouAEIOU":
v= v + 1
else:
c=c+1
elif St[i] in "0123456789":
d=d+1
else:
s=s+1
return v,c,d,s
def count2(St):
v=0
L = St.split()
print(L)
for i in range(len(L)):
if L[i][0] == 'A' or L[i][0] == 'a':
print(L[i])
v=v+1
return v
def word(St):
v=0
L = St.split()
print(L)
S=""
for i in range(len(L)):
if len(L[i])>v:
v = len(L[i])
S = L[i]
return v,S
def count3(St):
v=0
L= St.split()
print(L)
S= " "
for i in range(len(L)):
m = L[i].count('e')
if m > v:
v=m
S = L[i]
return S,v
ch='y'
while ch == 'y' or ch=='Y':
print("1. Enter string ")
print("2. Count no of spaces")
print("3. Count vowels, consonants, digits and special characters")
print("4. Count and display no of words starting with A or a ")
print("5. Longest word in a string ")
print("6. Display the word in which maximum times alphabet e appear")
x = int(input("Enter choice = "))
if x == 1:
St = input("Enter a string -> ")
print("Entered string is -> ", St)
if x == 2:
print("No of spaces = ",count(St))
if x == 3:
v,c,d,s=count1(St)
print("No of vowels ",v)
print("No of consonants ",c)
print("No of digits ",d)
print("No of special character",s)
if x == 4:
print("No of words starting with A or a ",count2(St))
if x == 5:
v,S = word(St)
print("longest word ", S, " Length is ", v)
if x == 6:
v,S = count3(St)
print("Word ", S, " is containing e ", v, "times")
ch = input("\nDo you want to continue Y/N = ")
1. Enter string
2. Count no of spaces
3. Count vowels, consonants, digits and special characters
4. Count and display no of words starting with A or a
5. Longest word in a string
6. Display the word in which maximum times alphabet e appear
Enter choice = 1
Enter a string -> Corona VIRUS 2020
Entered string is -> Corona VIRUS 2020

Do you want to continue Y/N = y


1. Enter string
2. Count no of spaces
3. Count vowels, consonants, digits and special characters
4. Count and display no of words starting with A or a
5. Longest word in a string
6. Display the word in which maximum times alphabet e appear
Enter choice = 2
No of spaces = 2

Do you want to continue Y/N = y


1. Enter string
2. Count no of spaces
3. Count vowels, consonants, digits and special characters
4. Count and display no of words starting with A or a
5. Longest word in a string
6. Display the word in which maximum times alphabet e appear
Enter choice = 3
No of vowels 5
No of consonants 6
No of digits 4
No of special character 2
Do you want to continue Y/N = y
1. Enter string
2. Count no of spaces
3. Count vowels, consonants, digits and special characters
4. Count and display no of words starting with A or a
5. Longest word in a string
6. Display the word in which maximum times alphabet e appear
Enter choice = 4
['Corona', 'VIRUS', '2020']
No of words starting with A or a 0
Do you want to continue Y/N = y
1. Enter string
2. Count no of spaces
3. Count vowels, consonants, digits and special characters
4. Count and display no of words starting with A or a
5. Longest word in a string
6. Display the word in which maximum times alphabet e appear
Enter choice = 5
['Corona', 'VIRUS', '2020']
longest word Corona Length is 6

Do you want to continue Y/N = y


1. Enter string
2. Count no of spaces
3. Count vowels, consonants, digits and special characters
4. Count and display no of words starting with A or a
5. Longest word in a string
6. Display the word in which maximum times alphabet e appear
Enter choice = 6
['Corona', 'VIRUS', '2020']
Word 0 is containing e times

Do you want to continue Y/N = n


# Program : 4
# Program to perform given operations on input String/sentence using UDF

c=0
ch='y'
v=c=d=s=0

def palin(St):
L = len(St)
j = L-1
f=0
for i in range(L):
if St[i] != St[j]:
f=1
j=j-1
if f==1:
print("String is not palindrome")
else:
print("String is palindrome")

def reverse(St):
L = len(St) - 1
St1 = ""
for i in range(L,-1,-1):
St1 = St1 + St[i]
print("Reversed string is ", St1)
def rev_word(St):
L = St.split()
x = len(L)
for i in L:
for j in range(len(i)-1, -1, -1):
print(i[j],end="")
print(" ",end="")
while ch == 'y' or ch=='Y':
print("1. Enter string ")
print("2. check it is palindrome or not")
print("3. create a string which is reverse of original string")
print("4. Print each word in reverse order ")
x = int(input("Enter choice = "))
if x == 1:
St = input("Enter a string -> ")
print("Entered string is -> ", St)
if x == 2:
palin(St)
if x == 3:
reverse(St)
if x == 4:
rev_word(St)
ch = input("\nDo you want to continue Y/N = ")
1. Enter string
2. check it is palindrome or not
3. create a string which is reverse of original string
4. Print each word in reverse order
Enter choice = 1
Enter a string -> My India
Entered string is -> My India

Do you want to continue Y/N = y


1. Enter string
2. check it is palindrome or not
3. create a string which is reverse of original string
4. Print each word in reverse order
Enter choice = 2
String is not palindrome

Do you want to continue Y/N = y


1. Enter string
2. check it is palindrome or not
3. create a string which is reverse of original string
4. Print each word in reverse order
Enter choice = 3
Reversed string is aidnI yM

Do you want to continue Y/N = y


1. Enter string
2. check it is palindrome or not
3. create a string which is reverse of original string
4. Print each word in reverse order
Enter choice = 4
yM aidnI
Do you want to continue Y/N = n
# Program : 5
# Program to show various logical operation on List
def search( L,x ):
f=0
for i in range(len(L)): Enter N5
if L[i]== x: Enter value8
f=1 Enter value6
print("Element exists at position ",i+1) Enter value9
if f==0: Enter value1
print("Element does not exit") Enter value4
1. Linear search
2. find highest element in a list
def highest(L):
3. Exchange first half with second
max = L[0]
half of a list
for i in L: Enter choice = 1
if i>max: Enter value to search 9
max = i Element exists at position 3
print("Greatest is ",max)
Do you want to continue Y/N = y
def Exchange( A ): 1. Linear search
N = len(A) 2. find highest element in a list
mid=N//2 3. Exchange first half with second
if N%2!=0: half of a list
mid=N//2 + 1 Enter choice = 2
Greatest is 9
for i in range(N//2):
A[i], A[mid + i] = A[mid + i], A[i]
Do you want to continue Y/N = y
1. Linear search
L = [] 2. find highest element in a list
n = int(input("Enter N")) 3. Exchange first half with second
for i in range(n): half of a list
x = int(input("Enter value")) Enter choice = 3
L.append(x) Original List is [8, 6, 9, 1, 4]
ch='y' The exchanged List is [1, 4, 9, 8, 6]
while ch == 'y' or ch=='Y':
print("1. Linear search ") Do you want to continue Y/N = n
print("2. find highest element in a list")
print("3. Exchange first half with second
half of a list")
x = int(input("Enter choice = "))
if x == 1:
a=int(input("Enter value to search "))
search( L,a )
if x == 2:
highest(L)
if x == 3:
print('Original List is ',L)
Exchange( L )
print ("The exchanged List is ", L)

ch = input("\nDo you want to continue Y/N = ")


# Program 6
# Write a function Div3and5() that takes a 10 elements numeric tuple and return the
#sum of elements which are divisible by 3 and 5

def Div3and5(t):
s=0
for i in t:
if i%3==0 and
i%5==0:
s=s+i
return s
#main
t=()
for i in range(10):
print("Enter the ",i+1,"th number of the tuple",end=" ",sep="")
e=int(input())
t = t + ( e, )
print("Entered tuple :",t)
print("Sum of numbers in tuple divisible by 3 and 5 =",Div3and5(t))

Enter the 1th number of the tuple 3


Enter the 2th number of the tuple 2
Enter the 3th number of the tuple 5
Enter the 4th number of the tuple 10
Enter the 5th number of the tuple 15
Enter the 6th number of the tuple 20
Enter the 7th number of the tuple 30
Enter the 8th number of the tuple 2
Enter the 9th number of the tuple 67
Enter the 10th number of the tuple 50
Entered tuple : (3, 2, 5, 10, 15, 20, 30, 2, 67, 50)
Sum of numbers in tuple divisible by 3 and 5 = 45
# Program 7
# Program to implement all methods/ functions of Dictionary
ch='y'
Stud = { }
while ch == 'y' or ch=='Y':
print("1. creating a dictionary")
print("2. Updating dictionary")
print("3. Printing the value of given key")
print("4. Delete element(s)")
print("5. Pop last element")
print("6. Empty Contents")
print("7. Copy dictionary")
print("8. Sort keys")
print("9. Use fromkeys function")
x = int(input("Enter choice = "))
if x == 1:
ch1 = 'y'
while ch1=='y':
key = input("Enter a key -> ")
val = input("Enter a value of key -> ")
Stud[key] = val
print(Stud)
ch1 = input("Do You want to add more items Y/N ")
if x == 2:
ch1 = 'y'
while ch1=='y':
key = input("Enter a key -> ")
val = input("Enter a value of key -> ")
Stud.update({key:val})
print(Stud)
ch1 = input("Do You want to update more Y/N ")
if x == 3:
key = input("Enter key whose value required ")
if key in Stud:
print(Stud[key])
else:
print("Not found") # print(Stud.get(key,"Not found"))
if x == 4:
print("1. To delete a particular element from dictionary")
print("2. To delete complete dictionary")
y = int(input("Enter the choice"))
if y == 1:
key = input("Enter a key to be deleted -> ")
Stud.pop(key) # del Stud[key]
print(Stud)
if y == 2:
del Stud
print(Stud) #this will cause an error because "Stud" no longer exists.
if x == 5:
Stud.popitem()
print(Stud)
if x == 6:
Stud.clear()
print(Stud)
if x == 7:
print("Stud ", Stud)
Stud1 = Stud
print("Stud1 = ",Stud1)
Stud1['Name'] = 'Rohan'
print("Stud after change in Stud1 ",Stud)
Stud2 = Stud.copy()
Stud2['Name'] = 'Romi'
print("stud after change is Stud2 ",Stud)
Stud3 = dict(Stud)
Stud3['Name'] = 'Vimal'
print("Stud after change in Stud 3 ",Stud)
if x == 8:
print(sorted(Stud))
if x == 9:
x = ('key1', 'key2', 'key3')
y = 0,1,2
thisdict = dict.fromkeys(x, y) #value if optional default value is none
print(thisdict)
ch = input("\nDo you want to continue Y/N = ")

1. creating a dictionary
2. Updating dictionary
3. Printing the value of given key
4. Delete element(s)
5. Pop last element
6. Empty Contents
7. Copy dictionary
8. Sort keys
9. Use fromkeys function
Enter choice = 1
Enter a key -> 1
Enter a value of key -> Arpit
{'1': 'Arpit'}
Do You want to add more items Y/N y
Enter a key -> 2
Enter a value of key -> Shaan
{'1': 'Arpit', '2': 'Shaan'}
Do You want to add more items Y/N n

Do you want to continue Y/N = y


1. creating a dictionary
2. Updating dictionary
3. Printing the value of given key
4. Delete element(s)
5. Pop last element
6. Empty Contents
7. Copy dictionary
8. Sort keys
9. Use fromkeys function
Enter choice = 2
Enter a key -> 2
Enter a value of key -> Sneh
{'1': 'Arpit', '2': 'Sneh'}
Do You want to update more Y/N y
Enter a key -> 3
Enter a value of key -> Vinay
{'1': 'Arpit', '2': 'Sneh', '3': 'Vinay'}
Do You want to update more Y/N n

Do you want to continue Y/N = y


1. creating a dictionary
2. Updating dictionary
3. Printing the value of given key
4. Delete element(s)
5. Pop last element
6. Empty Contents
7. Copy dictionary
8. Sort keys
9. Use fromkeys function
Enter choice = 3
Enter key whose value required 2
Sneh

Do you want to continue Y/N = y


1. creating a dictionary
2. Updating dictionary
3. Printing the value of given key
4. Delete element(s)
5. Pop last element
6. Empty Contents
7. Copy dictionary
8. Sort keys
9. Use fromkeys function
Enter choice = 4
1. To delete a particular element from dictionary
2. To delete complete dictionary
Enter the choice1
Enter a key to be deleted -> 2
{'1': 'Arpit', '3': 'Vinay'}

Do you want to continue Y/N = y


1. creating a dictionary
2. Updating dictionary
3. Printing the value of given key
4. Delete element(s)
5. Pop last element
6. Empty Contents
7. Copy dictionary
8. Sort keys
9. Use fromkeys function
Enter choice = 7
Stud {'1': 'Arpit', '3': 'Vinay'}
Stud1 = {'1': 'Arpit', '3': 'Vinay'}
Stud after change in Stud1 {'1': 'Arpit', '3': 'Vinay', 'Name': 'Rohan'}
stud after change is Stud2 {'1': 'Arpit', '3': 'Vinay', 'Name': 'Rohan'}
Stud after change in Stud 3 {'1': 'Arpit', '3': 'Vinay', 'Name': 'Rohan'}

Do you want to continue Y/N = y


1. creating a dictionary
2. Updating dictionary
3. Printing the value of given key
4. Delete element(s)
5. Pop last element
6. Empty Contents
7. Copy dictionary
8. Sort keys
9. Use fromkeys function
Enter choice = 5
{'1': 'Arpit', '3': 'Vinay'}

Do you want to continue Y/N = y


1. creating a dictionary
2. Updating dictionary
3. Printing the value of given key
4. Delete element(s)
5. Pop last element
6. Empty Contents
7. Copy dictionary
8. Sort keys
9. Use fromkeys function
Enter choice = 8
['1', '3']

Do you want to continue Y/N = y


1. creating a dictionary
2. Updating dictionary
3. Printing the value of given key
4. Delete element(s)
5. Pop last element
6. Empty Contents
7. Copy dictionary
8. Sort keys
9. Use fromkeys function
Enter choice = 6
{}

Do you want to continue Y/N = y


1. creating a dictionary
2. Updating dictionary
3. Printing the value of given key
4. Delete element(s)
5. Pop last element
6. Empty Contents
7. Copy dictionary
8. Sort keys
9. Use fromkeys function
Enter choice = 9
{'key1': (0, 1, 2), 'key2': (0, 1, 2), 'key3': (0, 1, 2)}

Do you want to continue Y/N = n


# Program : 8
‘’’ Program to store SRNO as key and NAME, TOTAL_MARKS as values
of n students in a Dictionary and perform the following:
(i) Print name, marks in descending order of marks
(ii) Print SRNO, NAME and TOTAL_MARKS of students whose name
begins with 'A' ‘’’

def disp(D):
L=[]
for i in D:
Enter no. of students 4
L.append(D[i][1])
Enter SRNO 1
L.sort(reverse=True)
Enter Name Aryan
j=0
Enter total marks 347
while L:
Enter SRNO 2
for i in D:
Enter Name Nikhil
if D[i][1]==L[j]:
Enter total marks 456
print(D[i][0],D[i][1])
Enter SRNO 3
L.remove(L[j])
Enter Name Prakhar
if L==[]:
Enter total marks 347
break
Enter SRNO 4
def Print(D):
Enter Name Manas
for i in D:
Enter total marks 467
if D[i][0][0]=='A':
print(i, D[i])
Merit List :
Stud={} Manas 467
n=int(input('Enter no. of students ')) Nikhil 456
for i in range(n): Prakhar 347
s=input('Enter SRNO') Aryan 347
a=input('Enter Name ')
Students with name
m=int(input('Enter total marks ')) beginning with A :
Stud[s]=[a,m] 1 ['Aryan', 347]
print('\nMerit List : ')
disp(Stud)
print('\nStudents with name beginning with A : ')
Print(Stud)
# Program : 9
# To create a text file “story.txt” with few lines of text. Read the file
# and print its contents along with number of vowels present in it

def Create():
f=open("story.txt","w")
a="Python is an interpreted,high-level,general-purpose programming\
language created by Guido Van Rossum and first released in the year 1991.\
Python's design philosophy emphasizes code readability. Its language\
constructs and object-oriented approach aim to help programmers write\
clear,logical code."
f.write(a)
f.close()

def count():
f=open("story.txt",'r')
st=f.read()
print("Contents of file :")
print(st)
c=0
v=['a','e','i','o','u']
for i in st:
if i.lower() in v:
c=c+1
print("*****FILE END*****")
print()
print("Number of vowels in the file =",c)
f.close()
Create()
count()

Contents of file :
Python is an interpreted,high-level,general-purpose programming language
created by Guido Van Rossum and first released in the year 1991. Python's
design philosophy emphasizes code readability. Its language constructs and
object-oriented approach aim to help programmers write clear,logical code.
*****FILE END*****

Number of vowels in the file = 92


# Program : 10 -> Program to perform various given operations on a text file

def CreateFile():
file1 = open("MyFile.txt","a")
c='y'
while c=='y' or c == 'Y':
file1.write(input('Enter line of text ')+'\n')
c=input('Want to add more y/n ')
file1.close()
def ReadFile(file):
file1 = open(file,"r")
St = file1.read()
print(St)
file1.close()
def Line():
f=open("MyFile.txt")
LINES=f.readlines()
for i in LINES:
line=i.rstrip()
if line[0]=='I' and line[-1]=='y':
print(line)
f.close()
def Count():
f=open("MyFile.txt")
c=0
words=f.read().split()
no=len(words)
for i in words:
if i.lower()=='the':
c=c+1
f.close()
print("Number of words: ",no)
print("Count of word 'the' : ",c)
def PrintLines():
f=open("abc.txt")
lines=f.readlines()
ctr=0
for line in lines:
word=line.split()
fword=word[0]
if len(fword)==1:
ctr+=1
print(line)
print("No. of lines =",ctr)
f.close()
def Write():
file1 = open("MyFile.txt","r")
file2 = open("temp.txt","w")
St = file1.read()
for i in St:
if i ==' ':
file2.write('#')
else:
file2.write(i)
file1.close()
file2.close()
ReadFile("temp.txt")
ch = 'y'
while ch=='y' or ch == 'Y':
print("1. To create file by adding lines of text ")
print ("2. To Display the file contents ")
print("3. To display lines starting with I and ending with y in file")
print("4. To find number of words and frequency of word 'the' in the file")
print("5. To count & print lines starting with words having single character ")
print("6. To create a new file by replacing space with # character ")
x = int(input("enter choice"))
if x == 1:
CreateFile()
if x == 2:
ReadFile("MyFile.txt")
if x == 3 :
Line()
if x==4:
Count()
if x==5:
PrintLines()
if x==6:
Write()
ch = input("Do You want to continue Y/N ")
1. To create file by adding lines of text
2. To Display the file contents
3. To display lines starting with I and ending with y in file
4. To find number of words and frequency of word 'the' in the file
5. To count & print lines starting with words having single character
6. To create a new file by replacing space with # character
enter choice1
Enter line of text Learning text files
Want to add more y/n n
Do You want to continue Y/N y
1. To create file by adding lines of text
2. To Display the file contents
3. To display lines starting with I and ending with y in file
4. To find number of words and frequency of word 'the' in the file
5. To count & print lines starting with words having single character
6. To create a new file by replacing space with # character
enter choice2
I liKe the python 4 programming
India is the fastest growing economy
Its a developing country
Learning text files
Do You want to continue Y/N y
1. To create file by adding lines of text
2. To Display the file contents
3. To display lines starting with I and ending with y in file
4. To find number of words and frequency of word 'the' in the file
5. To count & print lines starting with words having single character
6. To create a new file by replacing space with # character
enter choice3
India is the fastest growing economy
Its a developing country
Do You want to continue Y/N y
1. To create file by adding lines of text
2. To Display the file contents
3. To display lines starting with I and ending with y in file
4. To find number of words and frequency of word 'the' in the file
5. To count & print lines starting with words having single character
6. To create a new file by replacing space with # character
enter choice4
Number of words: 19
Count of word 'the' : 2
Do You want to continue Y/N y
1. To create file by adding lines of text
2. To Display the file contents
3. To display lines starting with I and ending with y in file
4. To find number of words and frequency of word 'the' in the file
5. To count & print lines starting with words having single character
6. To create a new file by replacing space with # character
enter choice5
I live in India

No. of lines = 1
Do You want to continue Y/N y
1. To create file by adding lines of text
2. To Display the file contents
3. To display lines starting with I and ending with y in file
4. To find number of words and frequency of word 'the' in the file
5. To count & print lines starting with words having single character
6. To create a new file by replacing space with # character
enter choice6
I#liKe#the#python#4#programming
India#is#the#fastest#growing#economy
Its#a#developing#country
Learning#text#files

Do You want to continue Y/N n


# Program : 11
# Program to implement all operations on a binary file

import pickle
import os
def add():
f = open("Myfile.dat","ab")
n = int(input("How many records "))
L=[]
for i in range(n):
roll = int(input("Enter Roll = "))
name = input("Enter name = ")
address = input("Enter address = ")
Fees = int(input("Enter the fees = "))
Stream = input("Enter the stream Sci/comm/Arts ")
T_No = int(input("Enter the teacher no who is teaching him"))
L = [roll,name,address,Fees,Stream,T_No]
pickle.dump(L,f)
f.close()
def read():
f = open("Myfile.dat","rb")
try:
while True:
L = pickle.load(f)
print(" Roll Number ", L[0])
print(" Name ", L[1])
print(" Address ", L[2])
print(" Fees ", L[3])
print(" Stream ", L[4])
print(" Teacher No ", L[5])
except:
f.close()
def Print():
f = open("Myfile.dat","rb")
Stream1 = input("Input Stream whose report required ")
print("________________________________________________")
L = []
S=0
print(" Roll Name Fees")
while True:
try:
L = pickle.load(f)
if Stream1 == L[4]:
print(L[0]," ",L[1]," ",L[3])
S = S + L[3]
except EOFError:
print("________________________________________________")
break
f.close()
print(" Sum of fees of ",Stream1," is = ",S)
def Del():
f = open("Myfile.dat","rb")
f1 = open("temp.dat","wb")
x = int(input("enter Roll no to be deleted "))
while True:
try:
L = pickle.load(f)
if L[0]!=x:
pickle.dump(L,f1)
except:
break
f.close()
f1.close()
os.remove("Myfile.dat")
os.rename("temp.dat","Myfile.dat")
def Update():
f = open("Myfile.dat","rb")
f1 = open("temp.dat","wb")
x = int(input("Enter Roll no whose fees need to be increase "))
while True:
try:
L = pickle.load(f)
if L[0]==x:
L[3] = L[3]+500
pickle.dump(L,f1)
else:
pickle.dump(L,f1)
except EOFError:
break
f.close()
f1.close()
os.remove("Myfile.dat")
os.rename("temp.dat","Myfile.dat")
def Create():
f = open("teacher.dat","wb")
n = int(input("How many records "))
L=[]
for i in range(n):
Tno = int(input("Enter Teacher No = "))
Tname = input("Enter Teacher name = ")
Dept = input("Enter depatrment= ")
Salary = int(input("Enter the Salary = "))
L = [Tno,Tname,Dept,Salary]
pickle.dump(L,f)
f.close()
def Search():
f = open("Myfile.dat","rb")
f1 = open("teacher.dat","rb")
n = int(input("enter roll no whose record is required "))
L,M, Temp=[],[],[]
Flag, Flag1 = 0,0
while True:
try:
L = pickle.load(f)
if n == L[0]:
Temp = L
Flag = 1
except EOFError:
print("")
break
if Flag == 0:
print("Student does not exists")
while True:
try:
M = pickle.load(f1)
if M[0] == Temp[5]:
print (" Roll No ",Temp[0])
print (" Student Name ",Temp[1])
print (" Teacher Name ",M[1])
print (" Department ",M[2])
Flag1=1
except EOFError:
print()
break
if Flag1==0:
print("Teacher Record does not exists")
f.close()
f1.close()
ch = 'y'
while ch == 'y' or ch == 'Y':
print("1. To Add records to a file of students ")
print("2. To read the Binary File ")
print("3. To Print report stream wise ")
print("4. To delete a record from Binary File ")
print("5. To Modify a record in a Binary File ")
print("6. To create a file of teachers")
print("7. Enter the roll and display the student name along with teacher name and
department")
x = int(input("Enter your choice = "))
if x == 1:
add()
if x == 2:
read()
if x == 3:
Print()
if x == 4:
Del()
if x == 5:
Update()
if x == 6:
Create()
if x == 7:
Search()
ch = input("Do You want to continue Y/N ")
1. To Add records to a file of students
2. To read the Binary File
3. To Print report stream wise
4. To delete a record from Binary File
5. To Modify a record in a Binary File
6. To create a file of teachers
7. Enter the roll and display the student name along with teacher name and department
Enter your choice = 1
How many records 1
Enter Roll = 2
Enter name = Sharad
Enter address = Hardoi
Enter the fees = 3500
Enter the stream Sci/comm/Arts Arts
Enter the teacher no who is teaching him102
Do You want to continue Y/N y
1. To Add records to a file of students
2. To read the Binary File
3. To Print report stream wise
4. To delete a record from Binary File
5. To Modify a record in a Binary File
6. To create a file of teachers
7. Enter the roll and display the student name along with teacher name and department
Enter your choice = 2
Roll Number 1
Name Arpan
Address Lko
Fees 2500
Stream Sci
Teacher No 101
Roll Number 2
Name Sharad
Address Hardoi
Fees 3500
Stream Arts
Teacher No 102
Do You want to continue Y/N y
1. To Add records to a file of students
2. To read the Binary File
3. To Print report stream wise
4. To delete a record from Binary File
5. To Modify a record in a Binary File
6. To create a file of teachers
7. Enter the roll and display the student name along with teacher name and department
Enter your choice = 3
Input Stream whose report required Sci
________________________________________________
Roll Name Fees
1 Arpan 2500
________________________________________________
Sum of fees of Sci is = 2500
Do You want to continue Y/N y
1. To Add records to a file of students
2. To read the Binary File
3. To Print report stream wise
4. To delete a record from Binary File
5. To Modify a record in a Binary File
6. To create a file of teachers
7. Enter the roll and display the student name along with teacher name and department
Enter your choice = 5
Enter Roll no whose fees need to be increase 1
Do You want to continue Y/N y
1. To Add records to a file of students
2. To read the Binary File
3. To Print report stream wise
4. To delete a record from Binary File
5. To Modify a record in a Binary File
6. To create a file of teachers
7. Enter the roll and display the student name along with teacher name and department
Enter your choice = 6
How many records 1
Enter Teacher No = 102
Enter Teacher name = Mrinal
Enter depatrment= English
Enter the Salary = 55000
Do You want to continue Y/N y
1. To Add records to a file of students
2. To read the Binary File
3. To Print report stream wise
4. To delete a record from Binary File
5. To Modify a record in a Binary File
6. To create a file of teachers
7. Enter the roll and display the student name along with teacher name and department
Enter your choice = 7
enter roll no whose record is required 2

Roll No 2
Student Name Sharad
Teacher Name Mrinal
Department English

Do You want to continue Y/N y


1. To Add records to a file of students
2. To read the Binary File
3. To Print report stream wise
4. To delete a record from Binary File
5. To Modify a record in a Binary File
6. To create a file of teachers
7. Enter the roll and display the student name along with teacher name and department
Enter your choice = 4
enter Roll no to be deleted 1
Do You want to continue Y/N y
1. To Add records to a file of students
2. To read the Binary File
3. To Print report stream wise
4. To delete a record from Binary File
5. To Modify a record in a Binary File
6. To create a file of teachers
7. Enter the roll and display the student name along with teacher name and department
Enter your choice = 2
Roll Number 2
Name Sharad
Address Hardoi
Fees 3500
Stream Arts
Teacher No 102
Do You want to continue Y/N n

# Program : 12
Given a PICKLED file “TRAIN.DAT” containing records OF TRAINS AS OBJECTS of TUPLE TYPE
WITH following STRUCTURE: (Train_No, Distance, Start_Place, End_Place)
a) WAF to write some records in file “TRAIN.DAT”.
b) Write a function to display THE DETAILS OF TRAINS RUNNING FROM ‘LUCKNOW’ TO ‘JAIPUR’ FROM
THE FILE “TRAIN.DAT”.
import pickle
def write():
x=open('TRAIN.DAT','wb')
ch='y'
while ch=='y' or ch=='Y': Enter Train Number 1101
Train_No= input("Enter Train Number ") Enter Distance 800
Distance=int(input("Enter Distance ")) Enter Train Source Delhi
Start_Place=input("Enter Train Source ") Enter Train Destination Lucknow
End_Place=input("Enter Train Destination ")
T=(Train_No,Distance,Start_Place,End_Place)
Want to write more y/n y
pickle.dump(T,x) Enter Train Number 1106
ch=input("Want to write more y/n ") Enter Distance 1100
x.close() Enter Train Source Lucknow
def display(): Enter Train Destination Jaipur
x=open('TRAIN.DAT','rb')
Want to write more y/n n
f=0
try: 1106 1100 Lucknow Jaipur
while True:
Rec=pickle.load(x)
if Rec[2].lower()=='lucknow' and Rec[3].lower()=='jaipur':
print(Rec[0],Rec[1],Rec[2],Rec[3], sep='\t')
f=1
except:
x.close()
if f==0:
print("No trains from Lucknow to Jaipur")
write()
display()
# Program : 13
=>WAF record() to add some records in a binary file "emp.dat" where records
are in the given format: {‘eno’:____,’ename’:____,’age’:____}
=>WAF sort() to write records of "emp.dat" in sorted manner in file
"sorted.dat" ( sorted in alphabetical order of 1st alphabet of name ).
=>WAF show() to display the contents of “sorted.dat” file.
WAP to invoke these functions.
import pickle
def record():
bf=open("emp.dat","ab")
ch='y'
d1={}
while ch=='y' or ch=='Y':
d1['eno']=int(input("enter employee number"))
d1['ename']=input("enter employee name")
d1['age']=int(input("enter age"))
pickle.dump(d1,bf)
ch=input("want to continue")
bf.close()
def sort():
for x in range(97,122):
bf2=open("emp.dat","rb")
bf1=open("sorted.dat","ab")
try :
while True:
d=pickle.load(bf2)
q=d['ename']
if q[0]==chr(x) or q[0]==chr(x-32):
pickle.dump(d,bf1)
except EOFError:
bf2.close()
bf1.close()
def show():
bf1=open("sorted.dat","rb")
enter employee number3
try :
while True:
enter employee nameFalak
d=pickle.load(bf1) enter age23
print(d['eno'],d['ename'],d['age'],sep='\t') want to continuen
except: 2 Amol 36
bf1.close() 3 Falak 23
record() 1 Kushagra 29
sort()
show()
# Program : 14
‘’’A text file “hobby.csv” contains name, phone no, hobby of students (shown
as below) :

 WAF to add records to the file


 WAF to read the file and display only names and hobby of the students
 WAF to input NAME of a STUDENT and display the hobby of the student
from the file.
WAP invoking above functions.’’’

import csv
def add():
f = open("hobby.csv", "a",newline='')
wr = csv.writer(f)
wr.writerow(['NAME','PHONENO','HOBBY'])
n=int(input("Enter no. of records.."))
for i in range(n):
name = input('Enter name ') Enter no. of records..1
phone = input('Enter phone no. ') Enter name Shreyas
hobby = input('Enter hobby ')
Enter phone no. 9867867894
wr.writerow([name, phone, hobby])
f.close() Enter hobby Volleyball
def read(): NAME HOBBY
fh=open("HOBBY.csv") NIMISHA LAWN TENNIS
STU=csv.reader(fh) NAMRATA CRICKET
for rec in STU: ANU CRICKET
print(rec[0],'\t\t', rec[2]) PANKAJ BASKET BALL
fh.close()
NAME HOBBY
def search():
fh=open("HOBBY.csv","r") Shreyas Volleyball
STU=csv.reader(fh) enter name of student...ANU
n=input("enter name of student...") ANU 's hobby is CRICKET
for rec in STU:
if (n==rec[0]):
print(rec[0]," 's hobby is ",rec[2])
fh.close()
add()
read()
search()
# Program : 15
WAP to execute the following using user defined functions on a text file
“emp.csv” :
 Display details of employees with salary between 30,000 to 70,000
 Read the file emp.csv and transfer records of all employees whose name
begins with ‘A’ to a new file
The file emp.csv contains following data : EMPID,ENAME, DESIG, SALARY

Sample CONTENT OF ‘emp.csv’

def search():
import csv
with open("emp.csv",newline='\r\n') as cfile1:
rec=csv.reader(cfile1)
m=next(rec) # heading row
for i in rec:
sal=int(i[3])
if sal>=30000 and sal<=70000:
print(i[0],i[1],i[2],i[3])
def transfer():
import csv
with open("emp.csv", 'r',newline= '\r\n') as f2, open("new_emp.csv", 'w') as f1:
rec=csv.reader(f2)
w = csv.writer(f1)
m=next(rec) # heading row
w.writerow(m)
for i in rec:
name=i[1]
if name[0]=='A':
w.writerow(i)
search()
transfer()
# Program : 16
# Program to demonstrate all operations on a stack implemented as a list

def push(stk,n):
stk.append(n)
def pop(stk):
if len(stk)==0:
print("UNDERFLOW CONDITION")
else:
Stack operations
print("Deleted element:",stk.pop()) 1.PUSH
def peek(stk): 2.POP
return stk[-1] 3.PEEK
def display(stk): 4.DISPLAY STACK
if len(stk)==0: 5.EXIT
print("No Element Present") Enter the choice1
else: Enter the element to PUSH 4500
for i in range(-1,-len(stk)-1,-1): Element pushed
if i==-1: Stack operations
print("TOP",stk[i]) 1.PUSH
else: 2.POP
3.PEEK
print(" ",stk[i])
4.DISPLAY STACK
#main 5.EXIT
stk=[] Enter the choice4
while True: TOP 4500
print(" Stack operations") Kush
print(" 1.PUSH") Stack operations
1.PUSH
print(" 2.POP")
2.POP
print(" 3.PEEK") 3.PEEK
print(" 4.DISPLAY STACK") 4.DISPLAY STACK
print(" 5.EXIT") 5.EXIT
ch=int(input(" Enter the choice")) Enter the choice3
if ch==1: 4500
n=input("Enter the element to PUSH ") Stack operations
push(stk,n) 1.PUSH
print("Element pushed") 2.POP
elif ch==2: 3.PEEK
pop(stk) 4.DISPLAY STACK
elif ch==3: 5.EXIT
Enter the choice2
if stk==[]:
Deleted element: 4500
print("UNDERFLOW CONDITION") Stack operations
else: 1.PUSH
print(peek(stk)) 2.POP
elif ch==4: 3.PEEK
display(stk) 4.DISPLAY STACK
elif ch==5: 5.EXIT
break Enter the choice4
else: TOP Kush
print("INVALID CHOICE ENTERED")
# Program : 17
#Python –MYSQL Connectivity ( To Insert, Display, Search, Modify, Delete
records in a Table created in a MySql database )
import mysql.connector
def insert():
cur.execute("desc {}".format(table_name))
data=cur.fetchall()
full_input=""
for i in data:
print("NOTE: Please enter string/varchar/date values (if any) in quotes")
print("Enter the",i[0],end=" ")
single_value=input()
full_input=full_input+single_value+","
full_input=full_input.rstrip(",")
cur.execute("Insert into {} values({})".format(table_name,full_input))
mycon.commit()
print("Record successfully inserted")
def display():
n=int(input("Enter the number of records to display "))
cur.execute("Select * from {}".format(table_name))
for i in cur.fetchmany(n):
print(i)
def search():
find=input("Enter the column name using which you want to find the record ")
print("Enter the",find,"of that record",end=" ")
find_value=input()
cur.execute("select * from {} where {}='{}'".format(table_name,find,find_value))
print(cur.fetchall())
def modify():
mod=input("Enter the field name to modify ")
find=input("Enter the column name using which you want to find the record ")
print("Enter the",find,"of that record",end=" ")
find_value=input()
print("Enter the new",mod,end=" ")
mod_value=input()
cur.execute("update {} set {}='{}' where {}='{}'".format( table_name, mod, mod_value, find,
find_value))
mycon.commit()
print("Record sucessfully modified")
def delete():
find=input("Enter the column name using which you want to find the record\nNOTE: NO
TWO RECORDS SHOULD HAVE SAME VALUE FOR THIS COLUMN: ")
print("Enter the",find,"of that record",end=" ")
find_value=input()
cur.execute("delete from {} where {}='{}'".format(table_name,find,find_value))
mycon.commit()
print("Record successfully deleted")
# main
database_name=input("Enter the database ")
my_sql_password=input("Enter the password for MySQL ")
table_name=input("Enter the table name ")
mycon=mysql.connector.connect(host="localhost",user="root",database=database_name,p
asswd=my_sql_password)
cur=mycon.cursor()
if mycon.is_connected():
print("Successfully Connected to Database")
else:
print("Connection Failed")

while True:
print("\t\t1. Insert Record")
print("\t\t2. Display Record")
print("\t\t3. Search Record")
print("\t\t4. Modify Record")
print("\t\t5. Delete Record")
print("\t\t6. Exit\n")
ch=int(input("Enter the choice "))
if ch==1:
insert()
elif ch==2:
display()
elif ch==3:
search()
elif ch==4:
modify()
elif ch==5:
delete()
elif ch==6:
mycon.close()
break
else:
print("Invalid choice entered")
Enter the database Rishabh
Enter the password for MySQL rlb#1
Enter the table name EMP
Successfully Connected to Database
1. Insert Record
2. Display Record
3. Search Record
4. Modify Record
5. Delete Record
6. Exit
Enter the choice 1
NOTE: Please enter string/varchar/date values (if any)
in quotes Enter the EMPNO 120
NOTE: Please enter string/varchar/date values (if any) in
quotes Enter the EMPNAME "Rishabh Rawat"
NOTE: Please enter string/varchar/date values (if any)
in quotes Enter the DEPT "Computer"
NOTE: Please enter string/varchar/date values (if any)
in quotes Enter the DESIGN "Coder"
NOTE: Please enter string/varchar/date values (if any)
in quotes Enter the basic 100000
NOTE: Please enter string/varchar/date values (if any)
in quotes Enter the CITY "Srinagar"
Record successfully inserted
1. Insert Record
2. Display Record
3. Search Record
4. Modify Record
5. Delete Record
6. Exit
Enter the choice 2
Enter the number of records to display 10
(111, 'Akash Narang', 'Account', 'Manager', 50000, 'Dehradun')
(112, 'Vijay Duneja', 'Sales', 'Clerk', 21000, 'lucknow')
(113, 'Kunal Bose', 'Computer', 'Programmer', 45000, 'Delhi')
(114, 'Ajay Rathor', 'Account', 'Clerk', 26000, 'Noida')
(115, 'Kiran Kukreja', 'Computer', 'Operator', 30000, 'Dehradun')
(116, 'Piyush Sony', 'Sales', 'Manager', 55000, 'Noida')
(117, 'Makrand Gupta', 'Account', 'Clerk', 16000, 'Delhi')
(118, 'Harish Makhija', 'Computer', 'Programmer', 34000, 'Noida')
(120, 'Rishabh Rawat', 'Computer', 'Coder', 100000, 'Srinagar')
1. Insert Record
2. Display Record
3. Search Record
4. Modify Record
5. Delete Record
6. Exit
Enter the choice 3
Enter the column name using which you want to find the record EMPNO
Enter the EMPNO of that record 120
[(120, 'Rishabh Rawat', 'Computer', 'Coder', 100000, 'Srinagar')]
1. Insert Record
2. Display Record
3. Search Record
4. Modify Record
5. Delete Record
6. Exit
Enter the choice 4
Enter the field name to modify basic
Enter the column name using which you want to find the record EMPNAME
Enter the EMPNAME of that record Rishabh Rawat
Enter the new basic 200000
Record sucessfully modified
1. Insert Record
2. Display Record
3. Search Record
4. Modify Record
5. Delete Record
6. Exit
Enter the choice 5
Enter the column name using which you want to find the record
NOTE: NO TWO RECORDS SHOULD HAVE SAME VALUE FOR THIS COLUMN: EMPNO
Enter the EMPNO of that record 120
Record successfully deleted
# Program : 18
#Python –MYSQL Connectivity : to display all records where student name
# ends with a given char from a SQL database

def fun(x):
import mysql.connector as c
m=c.connect(host="localhost",user="root",passwd="",database="student")
cur=m.cursor()
cur.execute("select * from stud where name like '%{}'".format(x))
d=cur.fetchall()
for x in d:
print(x)
m.close()
fun('u')

(10,‘Nishu’,’M’,2000,67 )
(16,’Anshu’,‘F’,3550, 60 )

# Program : 19
‘’’Python –MYSQL Connectivity : WAF to display following information from
the student table:
i) minimum and maximum fee amount
ii) total fee amount iii) average of fee ‘’’

def fun():
import mysql.connector as c
m=c.connect(host="localhost",user="root",passwd="",database="student")
cur=m.cursor()
print("Min. fee Max. fee")
cur.execute("select min(fees),max(fees)from stud")
d=cur.fetchone()
print(d[0],d[1],sep=" ")
cur.execute("select sum(fees)from stud")
d=cur.fetchone()
print("Total amount of fees", end=':')
print(d[0])
cur.execute("select avg(fees)from stud")
d=cur.fetchone()
print("Average amount of fees", end=':')
print(d[0])
m.close()

fun()
# Program : 20
‘’’Python –MYSQL Connectivity : WAF to receive a field name and datatype as
parameters and perform following task:
1) Add that field in the stud table existing in student database.
2) Fill the new column with 0 if datatype is int and "X" if datatype is char.
3) Display the entire content from the table. ‘’’

def fun(x,y):
import mysql.connector as c
a='X'
m=c.connect(host="localhost",user="root",passwd="",database="student")
cur=m.cursor()
cur.execute("Alter table stud add {} {}".format(x,y))
if y=="int":
cur.execute("update stu2 set {}={}".format(x,0))
else:
cur.execute("update stu2 set {}='{}'".format(x,a))
cur.execute("select * from stu2")
d=cur.fetchall()
for x in d:
print(x)
m.close()

fun('prize','int')

You might also like