0% found this document useful (0 votes)
70 views23 pages

Class 12 Practical Programs 1-14

The document contains examples of Python programs to solve different problems. It includes programs to print the Fibonacci series, check palindromes, find largest and smallest items in a list, calculate area of shapes, use dictionaries to search data, generate random numbers, separate words with symbols, and print lines starting with certain characters.

Uploaded by

Ben Dover
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
70 views23 pages

Class 12 Practical Programs 1-14

The document contains examples of Python programs to solve different problems. It includes programs to print the Fibonacci series, check palindromes, find largest and smallest items in a list, calculate area of shapes, use dictionaries to search data, generate random numbers, separate words with symbols, and print lines starting with certain characters.

Uploaded by

Ben Dover
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 23

Ex.

no: 01 Fibonacci Series


Problem:
Write a Python program to print Fibonacci Series for given n number
of terms using function.

Aim:
To write a Python program to print Fibonacci Series for given n number of
terms using function

Program Coding:
def Fibonacci(n):
t1 = -1
t2 = 1
for i in range(n):
t3 = t1+ t2
print(t3,end = " ")
t1 = t2
t2 = t3
print("Fibonacci Series")
n = int(input("Enter the number of terms you want to
print: "))
Fibonacci(n)

Output: [To be written on the left hand side of the record


note with pencil]
Fibonacci Series
Enter the number of terms you want to print: 10
0 1 1 2 3 5 8 13 21 34

Result: Thus the program to print the Fibonacci series has been
executed successfully and the output is verified.

Ex.no: 02 Palindrome
Problem:
Write a Python program to check whether the given string
is a palindrome or not.
Aim:
To write a Python program to check whether the given string is a
palindrome or not.
Program Coding:
def Palindrome(L):
for i in (0,L//2):
if S[i] != S[L-i-1]:
print("The given string",S," is not a Palindrome")
break
else:
print("The given string",S," is a Palindrome")

S = input("Enter a string: ")


L = len(S)
Palindrome(L)

Output: [To be written on the left hand side of the record


note with pencil]
Enter a string: madam
The given string madam is a Palindrome

Enter a string: Malayalam


The given string Malayalam is not a Palindrome

Result: Thus the program to check whether the given string is a


palindrome or not, has been executed successfully and the output is
verified.

Ex.no: 03 Printing the largest and smallest name in a list


Problem:
Write a Python program to create a list with different country names
and print the largest and the smallest c o u n t r y n
a m e using function
Aim:
To write a Python program to create a list with different country
names and print the largest and the smallest c o u n t ry n a me (by
counting the number of characters) using function.
Program Coding:
def MaxMin(n):
Country = []
for i in range(n):
cname = input('Enter the country name: ')
Country.append(cname)
Country.sort(key=len)
print('Country name with the smallest length = ,Country[0])
print('Country name with the largest length =',Country[len(Country)-1])

n = int(input('Enter the no. of countries: '))


MaxMin(n)
Output:
Enter the no. of countries: 5
Enter the country name:
Japan
Enter the country name:
Canada
Enter the country name:
Srilanka
Enter the country name: USA
Enter the country name:
Russia
Country name with the smallest length = USA
Country name with the largest length = Srilanka

Result: Thus the program to print the largest and the smallest c o u
nt r y name using function has been executed successfully and the
output is verified.

Ex.no: 04 Menu driven program to calculate area of


different shapes
Problem:
Write a Python program to develop a menu driven
program to calculate the area of different shapes using
functions.

Aim:
To write a Python program to develop a menu driven program to
calculate the area of different shapes using functions.

Program Coding:

def Area(Choice):
if Choice == 1:
side = int(input('Enter your side value: '))
area_sq = side * side
print('Area of a square = ',area_sq)
elif Choice == 2:
length = int(input('Enter the Length value: '))
breadth = int(input('Enter the Breadth value: '))
area_rec = length * breadth
print('Area of a rectangle = ',area_rec)
elif Choice == 3:
base = int(input('Enter the base value: '))
height = int(input('Enter the height value: '))
area_tri = 0.5 * base * height
print('Area of a triangle = ',area_tri)
elif Choice == 4:
exit
ch='y'
while ch=='y' or ch=='Y':

print('\n Menu Driven Program to Compute the Area of different


shapes')
print('1. Area of a square')
print('2. Area of a rectangle')
print('3. Area of a triangle')
print('4. Exit')
Choice = int(input('Enter your choice between 1 to 4: '))
if Choice < 1 or Choice > 4:
print('Wrong Choice')
else:
Area(Choice)
ch=input("Do you want to continue (y/n)")

Output:
Menu Driven Program to Compute the Area of different
shapes
1. Area of a square
2. Area of a rectangle
3. Area of a triangle
4. Exit
Enter your choice between
1 to 4: 1
Enter your side value: 10
Area of a square = 100
Do you want to continue (y/n) : y
Menu Driven Program to Compute the Area of different shapes

1. Area of a square
2. Area of a rectangle
3. Area of a triangle
4. Exit
Enter your choice between 1 to 4: 2
Enter the Length value: 20
Enter the
Breadth
value: 30
Area of a
rectangle =
600
Do you want to continue (y/n) : y

Menu Driven Program to Compute the Area of different shapes


1. Area of a square
2. Area of a rectangle
3. Area of a triangle
4. Exit
Enter your choice between 1 to
4: 3
Enter the base value: 25
Enter the
height
value: 50
Area of a
triangle =
625.0
Do you want to continue (y/n) : y

Menu Driven Program to Compute the Area of different shapes


1. Area of a square
2. Area of a rectangle
3. Area of a triangle
4. Exit
Enter your choice between 1 to 4: 4
Do you want to continue (y/n) : y
Menu Driven Program to Compute the Area of different shapes

1. Area of a square
2. Area of a rectangle
3. Area of a triangle
4. Exit
Enter your choice
between 1 to 4: 56
Wrong Choice
Do you want to continue (y/n) : n

Result: Thus the program to develop a menu driven program to calculate


the area of different shapes using functions has been executed
successfully and the output is verified.

Ex.no: 05 Search and display- using dictionary


Problem:
Write a Python program to create a dictionary to store roll number
and name of 5 students. Display the corresponding name for the
given Roll number, if it is not found then display appropriate error
message.
Aim:
To write a Python program to create a dictionary to store roll
number and name of 5 students, for a given roll number display
the corresponding name else display appropriate error message.

Program Coding:
myDict = {}
def CreateDict():
for i in range(5):
rno = int(input('Enter the rollno: '))
name = input('Enter the name: ')
myDict[rno] = name
print(myDict)

def Search(n):
found = 0
for i in myDict:
if i == n:
found = 1
print("The element is found in the dictionary")

print("The element is : ")


print("Roll No : ",i,' ',"name : ",myDict[i])
break
if found == 0:
print(n, 'is not found in the dictionary')

CreateDict()
n = int(input('Enter the key to be searched: '))
Search(n)
Output :

Enter the rollno: 1


Enter the name: Chandru
Enter the rollno: 2
Enter the name: Ajay
Enter the rollno: 3
Enter the name: Vinitha
Enter the rollno: 4
Enter the name: Fathima
Enter the rollno: 5
Enter the name: Banu
{1: 'Chandru', 2: 'Ajay', 3: 'Vinitha', 4: 'Fathima', 5: 'Banu'}
Enter the key to be searched: 3
The element is found in the dictionary'
The element is:
Roll.No : 3 Name :Vinitha

Enter the rollno: 1


Enter the name: Saranya
Enter the rollno: 2
Enter the name: Suji
Enter the rollno: 3
Enter the name: Aswin
Enter the rollno: 4
Enter the name: Arun
Enter the rollno: 5
Enter the name: Vinay
{1: ' Saranya ', 2: ' Suji', 3: ' Aswin ', 4: ' Arun ', 5: ' Vinay '}
Enter the key to be searched: 8
The element is not found in the
dictionary

Result: Thus the program to create a dictionary and to search a


given key, has been executed successfully and the output is verified.

Ex.no: 6 Random number


generation
Problem:
Write a Python program to generate random numbers between 1 to 6
(stimulate a dice)
Aim:
To write a Python program to generate random numbers between 1 to
6 (stimulate a dice)
Program Coding:

import random
Guess = True
while Guess:
n = random.randint(1,6)
userinput = int(input("Enter a number between 1 to 6: "))
if userinput == n:
print("Congratulations!!!,You won the lottery")
else:
print("Sorry, Try again, The lucky number was: ",n)
val = input("Do you want to continue y/n: ")
if val in ['y','Y']:
Guess = True
else:
Guess = False

Output:

Enter a number between 1 to 6: 2


Sorry, Try again, The lucky number was: 4
Do you want to continue y/n: y
Enter a number between 1 to 6: 3
Sorry, Try again, The lucky number was: 2
Do you want to continue y/n: y
Enter a number between 1 to 6: 5
Sorry, Try again, The lucky number was:
4
Do you want to continue y/n: y
Enter a number between 1 to 6: 2
Congratulations!!!,You won the lottery
Do you want to continue y/n: n
Result:
The program to generate random numbers between 1 to 6
(stimulate a dice) has been executed successfully and the output is
verified.

Ex. No. 7 Separating words by ‘#’ symbol

Problem:
Write a program to read a text file line by line and
d i s p l a y ’ # ’ a f t er each word.

Aim:
To w r i t e a p r o g r a m t o read a text file, line by line and display each
word separated by ‘#’.

Program Coding :
def addHash():
with open('Mystory.txt') as F:
Lines = F.readlines()
myList = []
for i in Lines:
myList = i.split()
for j in myList:
print(j,"#",end= " ")
addHash()
The content of “Mystory.txt” file:
Python is a Programming language. It is easy to learn.

Output:
Python # is # a # Programming # language. # It # is # easy # to #
learn. #

Result:
The above program has been executed successfully and the output is
verified.

Ex.No. 8 Printing all the lines starting with ‘T’ or ‘P’


Problem:
Write a program to read a text file and print all the lines that are
starting with ‘T’ or ‘P’.
Aim:
To write a program to read a text file and print all the lines that are
starting with ‘T’ or ‘P’ on the screen.
Program Coding:
def printlines():
with open('Myfile.txt') as F:
R = F.readlines()
for line in R:
if line[0].upper() == 'T' or line[0].upper() == 'P':
print(line)
printlines()

Content of the input file “Myfile.txt”


This is the first line of my file . I want to
Print the lines starting with the letter 'T" or "P"
so this line will not be printed.
this line starts with 't' not 'T' but it is changed into Uppercase.

Output :
This is the first line of my file . I want to

Print the lines starting with the letter 'T" or "P"

this line starts with 't' not 'T' but it is changed into
Uppercase.
Result: The above program has been executed successfully and the
output is verified.
Ex.No.9 Counting the number of occurrences of ‘is’
and ‘ and‘ in a text file
Problem :
Write a program to read a text file and count the number of
occurrences of ‘is’ and ‘and’ in that file.

Aim:
To write a program to read a text file and count the number of
occurrences of ‘is’ and ‘and’ in that file.
Program Coding:
def Counting():
with open('Mystory.txt','r') as rfile:
R = rfile.readlines()
print(R)
iscount=andcount = 0
for line in R:
words = line.split()
for i in words:
if i == 'is':
iscount+=1
elif i=='and' :
andcount+=1
print('The total no. of words with is = ',iscount )
print('The total no. of words with and = ', andcount)
Counting()

The content of “Mystory.txt”: [to be written on left side of the


record note]

Python is a Programming language and It is used to solve


problems .
It is easy to learn and i like it very much.
Output:
['Python is a Programming language and It is used to solve
problems .\n', 'It is easy to learn and i like it very much.\n']
The total no. of words with is = 3
The total no. of words with and = 2
Result:
The above program has been executed and the output is verified
successfully
Ex.No.10
Counting vowels, consonants, digits, special characters,
lower case & upper case letters
Problem:
Write a program to count the number of vowels, consonants, digits,
special characters, lower case & upper case letters present in a text
file and display the same.
Aim:
To Write a program to count the number of vowels, consonants,
digits, special characters, lower case & upper case letters present in
a text file and display the same.

Program Coding:

import string
def TextFileCounting():
ucase = 0
lcase = 0
vowels = 0
consonants = 0
digits = 0
special = 0
cspace=0
with open('Mytextfile.txt') as rtextfile:
Read = rtextfile.read()
for ch in Read:
if ch.isalpha():
if ch in ['a','e','i','o','u','A','E','I','O','U']:
vowels+=1
else:
consonants+=1
if ch.isupper():
ucase+=1
elif ch.islower():
lcase+=1
elif ch.isdigit():
digits+=1
elif ch==" ":
cspace=cspace+1
else:
special+=1
print('No of uppercase alphabets = ',ucase)
print('No of lowercase alphabets = ',lcase)
print('No of digits = ',digits)

print('No of vowels = ',vowels)


print('No of consonants = ',consonants)
print('No of spaces = ',cspace)
print('No of special characters = ',special)
print('Total no. of characters in the file =', len(Read))
TextFileCounting()

Content of “'Mytextfile.txt'” file


Python programming language was developed by Guido Van Rossum in 1991.
Python is an easy-to-learn yet powerful object oriented programming language.

Output:
No of uppercase alphabets = 5
No of lowercase alphabets = 116
No of digits = 4
No of vowels = 46
No of consonants = 75
No of spaces = 20
No of special characters = 6
Total no. of characters in the file = 151
Result:
The above program has been executed successfully and the output is
verified.

EX.NO.11 Search a Member No. and display using binary file

Problem:
Write a program to create a binary file to store member no and
member name. Search the given member no. and display its
associated name else display appropriate error message.

Aim: To create a binary file to store member no and member name


and to Search the given a member no, display its associated name
else display appropriate error message.
Program Coding:
import pickle
Member = {}
def Store_binary_info():
with open('member.dat','ab') as wbfile:
while True:
Mno = int(input('Enter the Member no: '))
name = input('Enter the name: ')
Member['MemberNo'] = Mno
Member['Name'] = name
pickle.dump(Member,wbfile)
ch = input('Do you want to continue y/n :')
if ch == 'n':
print('Binary File writing is over')
break

def Search_info():
with open('member.dat','rb') as rbfile:
mno = int(input('Enter the member no. to be
searched:'))
try:
while True:
Member = pickle.load(rbfile)
if Member['MemberNo'] == mno:
print (Member)
break
except EOFError:
print('Member No not found')
Store_binary_info()
Search_info()
Output :
Enter the Member no: 11
Enter the name: Venkat
Do you want to continue y/n :y
Enter the Member no: 12
Enter the name: Mala
Do you want to continue y/n :y
Enter the Member no: 13
Enter the name: Vijay
Do you want to continue y/n :n
Binary File writing is over
Enter the member no. to be searched:13
{'MemberNo': 13, 'Name': 'Vijay'}

Enter the Member no: 14


Enter the name: Raji
Do you want to continue y/n :y
Enter the Member no: 15
Enter the name: Ajay
Do you want to continue y/n :n
Binary File writing is over
Enter the member no to be searched:10
Member No not found
Result:
The above program has been executed successfully and the output is
verified.
EX.NO.12 Menu driven program to manipulate data on to
a binary file.

Problem:
Write a program to create a menu driven program to write, read,
update and append data on to a binary file.

Aim: To create a menu driven program to write, read, update and


append data on to a binary file.
Program Coding:

import pickle
Member = {}

def Writing_Binary():
with open('member.dat','wb') as wbfile:
while True:
Mno = int(input('Enter the member no: '))

name = input('Enter the name: ')


Member['MemberNo'] = Mno
Member['Name'] = name
pickle.dump(Member,wbfile)
ch = input('Do you want to continue y/n :')
if ch == 'n':
print('Binary File writing is over')
break

def Read_Binary():
with open('member.dat','rb') as rbfile:
try:
while True:
Member = pickle.load(rbfile)
print(Member)
except EOFError:
print('Finished reading binary file')

def Update_Binary():
found = False
with open('member.dat','rb+') as rbfile:
try:
while True:
rpos = rbfile.tell()
Member = pickle.load(rbfile)
if Member['Name'] == 'John':
Member['Name'] = 'Johnson'
rbfile.seek(rpos)
pickle.dump(Member,rbfile)
print(Member)
found = True
break
except EOFError:
if found == False:
print('Data not updated in the file')
else:
print('Data updated successfully')
def Append_Binary():
with open('member.dat','ab') as wbfile:
while True:
Mno = int(input('Enter the member no: '))
name = input('Enter the name: ')
Member['MemberNo'] = Mno
Member['Name'] = name
pickle.dump(Member,wbfile)
ch = input('Do you want to continue y/n :')

if ch == 'n':
print('Binary File writing is over')
break
while True:
print(' ')
print('Menu Driven Programming')
print(' ')
print('1. Create a binary file')
print('2. Read the data from binary file ')
print('3. Update the binary file')
print('4. Append data to the binary file')
print('5. Exit')
ch = int(input('Enter your choice: '))
if ch == 1:
Writing_Binary()
elif ch == 2:
Read_Binary()
elif ch == 3:
Update_Binary()
elif ch == 4:
Append_Binary()
elif ch == 5:
break

Output:
Menu Driven Programming

1. Create a binary file


2. Read the data from binary file
3. Update the binary file
4. Append data to the binary file
5. Exit
Enter your choice: 1
Enter the member no: 1
Enter the name: John
Do you want to continue y/n :y
Enter the member no: 2
Enter the name: Kavin
Do you want to continue y/n :y
Enter the member no: 3
Enter the name: Ajay
Do you want to continue y/n :n
Binary File writing is over

Menu Driven Programming

1. Create a binary file


2. Read the data from binary file
3. Update the binary file
4. Append data to the binary file
5. Exit
Enter your choice: 2
{'MemberNo': 1, 'Name': 'John'}
{'MemberNo': 2, 'Name': 'Kavin'}
{'MemberNo': 3, 'Name': 'Ajay'}
Finished reading binary file

Menu Driven Programming

1. Create a binary file


2. Read the data from binary file
3. Update the binary file
4. Append data to the binary file
5. Exit
Enter your choice: 3
{'MemberNo': 1, 'Name': 'Johnson'}

Menu Driven Programming

1. Create a binary file


2. Read the data from binary file
3. Update the binary file
4. Append data to the binary file
5. Exit
Enter your choice: 4
Enter the member no: 5
Enter the name: kavin
Do you want to continue y/n :n
Binary File writing is over

Menu Driven Programming

1. Create a binary file


2. Read the data from binary file
3. Update the binary file
4. Append data to the binary file
5. Exit
Enter your choice: 5
Result:
The above program has been executed successfully and the output is
verified.

Ex.No :13 Storing and retrieving data using csv file


Problem:
Write a program to store and retrieve student’s
details using csv file.
Aim:
To Write a program to store and retrieve student’s details using
csv file.
Program Coding:
import csv
stu = []
def write_data():
with open('InputData.csv','a',newline='') as F:
write = csv.writer(F)
ch = 'y'
while ch == 'y':
name = input('Enter the student name:')
totalmarks = int(input('Total marks:'))
stu = [name,totalmarks]
write.writerow(stu)
ch = input('Do you want to continue y/n: ')

def read_data():
with open('InputData.csv','r') as F:
Reader = csv.reader(F)
for Data in Reader:
print(Data[0],int(Data[1]),int(Data[1])/5)
write_data()
read_data()
Output:
Enter the student name: Kavitha
Total marks:78
Do you want to continue y/n: y
Enter the student name: Kavin
Total marks:90
Do you want to continue y/n: y
Enter the student name: John
Total marks:44
Do you want to continue y/n: n
kavitha 78 15.6
Kavin 90 18.0
john 44 8.8

Result: The above program has been executed successfully and the
output is verified.
Ex.No.14 Copying the contents of one csv file to another file

Problem:
Write a program to copy the contents of a csv file into another
csv file using different delimiter.
Aim:
To write a program to copy the contents of a csv file into another csv
file using different delimiter.
Program Coding:

import csv
def copy_data():
with open('InputData.csv') as F1:
with open('Infile.csv','w',newline='') as F2:
Read = csv.reader(F1)
write = csv.writer(F2,delimiter= '#')
for line in Read:
write.writerow(line)
def disp_data():
with open('Infile.csv') as F:
Reader = csv.reader(F)
for Data in Reader:
print(Data)
copy_data()
disp_data()

Output:
['100#Hamam#28']
['101#Cinthol#29']
['102#Dove#45']

Result:
The above program has been executed successfully and the output is
verified.

You might also like