Python Programs For Practicals
Python Programs For Practicals
TIME : MARKS :
1.Lab Test
Q1.PYTHON PROGRAM
(i)Write a program in Python to accept a string and count the vowels , consonant ,
digits and special characters in string.Special characters also contain the white
space.
def countCharacterType(str):
vowels = 0
consonant = 0
specialChar = 0
digit = 0
# str.length() function to count
# number of character in given string.
fori in range(0, len(str)):
ch = str[i]
if ( (ch>= 'a' and ch<= 'z') or
(ch>= 'A' and ch<= 'Z') ):
# To handle upper case letters
ch = ch.lower()
if (ch == 'a' or ch == 'e' or ch == 'i'
orch == 'o' or ch == 'u'):
vowels += 1
else:
consonant += 1
elif (ch>= '0' and ch<= '9'):
digit += 1
else:
specialChar += 1
print("Vowels:", vowels)
print("Consonant:", consonant)
print("Digit:", digit)
print("Special Character:", specialChar)
str = "LMD SCHOOL Chennai 94"
countCharacterType(str)
Q2.PYTHON PROGRAM
i. Write a user defined function createFile() to input data for a record and add to
Book.dat.
ii. Write a function countRec(Author) in Python which accepts the Author name as
parameter and count and return number of books by the given Author are stored in
the binary file "Book.dat”
import pickle
defcreateFile():
file = open("book.dat","ab")
BookNo = int(input("Enter book number: "))
Book_Name = input("Enter book Name: ")
Author =input("Enter author: ")
Price = int(input("Enter price: "))
record = [BookNo, Book_Name, Author, Price]
pickle.dump(record, file)
file.close()
defcountRec(Author):
file = open("book.dat","rb")
count = 0
try:
while True:
record = pickle.load(file)
if record[2]==Author:
count+=1
exceptEOFError:
pass
return count
file.close()
#To test working of functions
deftestProgram():
while True:
createFile()
choice = input("Add more record (y/n)? ")
if choice in 'Nn':
break
Author = input('Enter author name to search: ')
n = countRec(Author)
print("No of books are",n)
testProgram()
Q3.PYTHON PROGRAM
Write a program to perform read and write operation with .csv file.
Q4.PYTHON PROGRAM
(i)Write a function in python to count the number of lines from a text file
"story.txt" which is not starting with an alphabet "T".
Example: If the file "story.txt" contains the following lines:
PROGRAM
defline_count():
file= open("story.txt","r")
count=0
for line in file:
if line[0]notin'T':
count+=1
file.close()
print("No of lines not starting with 'T'=",count)
line_count()
Q5.PYTHON PROGRAM