2022 Term01 Practicals

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 24

Expno: 01 Fibonacci Series Pgno: 01

Date:

Aim: To print Fibonacci Series using function

Program:

def Fibonacci(n):
firsterm = -1
secondterm = 1
for i in range(n):
thirdterm = firsterm + secondterm
print(thirdterm,end = " ")
firsterm = secondterm
secondterm = thirdterm
print("Fibonacci Series")
n = int(input("Enter the number of terms you want to print: "))
Fibonacci(n)

Sample Input and Output: [To be written on the left hand side of the record note]

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

Result: The above program has been executed successfully


Program 02: Palindrome

Aim: To check whether a given string is a palindrome or not.

Program:

def Palindrome(myLength):
for i in (0,myLength//2):
if myString[i] != myString[myLength-i-1]:
print("The given string",myString," is not a Palindrome")
break
else:
continue
else:
print("The given string",myString," is a Palindrome")

print("Palindrome Check")
myString = input("Enter a string: ")
myLength = len(myString)
Palindrome(myLength)

Sample Input and Output: [To be written on the left hand side of the record note]

Palindrome Check
Enter a string: Madam
The given string Madam is not a Palindrome

Palindrome Check
Enter a string: MalayalaM
The given string MalayalaM is a Palindrome

Result: The above program has been executed successfully


Program 03: Printing the largest and smallest country name in a list

Aim: To create a list with different country names and print the largest and the smallest
country (by counting the number of characters) using function.

Program:

def MaxMin(n):
Country = []
for i in range(n):
cname = input('Enter the country name: ')
Country.append(cname)
Country.sort(key=len)
print('Country with the smallest length = ',Country[0])
print('Country with the largest length = ',Country[len(Country)-1])
n = int(input('Enter the no. of country: '))
MaxMin(n)

Sample Input and Output: [To be written on the left hand side of the record note]

Enter the no. of country: 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 with the smallest length = USA
Country with the largest length = Srilanka

Result: The above program has been executed successfully


Program 04: Menu driven program to calculate area of different shapes

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

Program:

def Area(Choice):
if Choice == 1:
side = int(input('Enter your side value: '))
areasq = side * side
print('Area of a square = ',areasq)
elif Choice == 2:
length = int(input('Enter the Length value: '))
breadth = int(input('Enter the Breadth value: '))
arearec = length * breadth
print('Area of a rectangle = ',arearec)
elif Choice == 3:
base = int(input('Enter the base value: '))
height = int(input('Enter the height value: '))
areatri = 0.5 * base * height
print('Area of a triangle = ',areatri)
elif Choice == 4:
exit
print('Menu Driven Program to Compute the Area of different shapes')
print('-----------------------------------------------------------')
print('1. To compute area of a square')
print('2. To compute area of a rectangle')
print('3. To compute 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)
Sample Input and Output: [To be written on the left hand side of the record note]
Menu Driven Program to Compute the Area of different shapes
-----------------------------------------------------------
1. To compute area of a square
2. To compute area of a rectangle
3. To compute area of a triangle
4. Exit
Enter your choice between 1 to 4: 1
Enter your side value: 10
Area of a square = 100
Menu Driven Program to Compute the Area of different shapes
-----------------------------------------------------------
1. To compute area of a square
2. To compute area of a rectangle
3. To compute 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
Menu Driven Program to Compute the Area of different shapes
-----------------------------------------------------------
1. To compute area of a square
2. To compute area of a rectangle
3. To compute 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
Menu Driven Program to Compute the Area of different shapes
-----------------------------------------------------------
1. To compute area of a square
2. To compute area of a rectangle
3. To compute area of a triangle
4. Exit
Enter your choice between 1 to 4: 4
Menu Driven Program to Compute the Area of different shapes
-----------------------------------------------------------
1. To compute area of a square
2. To compute area of a rectangle
3. To compute area of a triangle
4. Exit
Enter your choice between 1 to 4: 56
Wrong Choice

Result: The above program has been executed successfully


Program 05: Search and display using dictionary

Aim: 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:
myDict = {}
def InputDictionary():
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')
print(i,' ',myDict[i])
break
if found == 0:
print(n,' is not found in the dictionary')

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

Sample Input and Output: [To be written on the left hand side of the record note]
Enter the rollno: 1
Enter the name: a
Enter the rollno: 2
Enter the name: b
Enter the rollno: 3
Enter the name: c
Enter the rollno: 4
Enter the name: d
Enter the rollno: 5
Enter the name: e
{1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}
Enter the key to be searched: 3
The element is found
3 c

Enter the rollno: 1


Enter the name: a
Enter the rollno: 2
Enter the name: b
Enter the rollno: 3
Enter the name: c
Enter the rollno: 4
Enter the name: d
Enter the rollno: 5
Enter the name: e
{1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}
Enter the key to be searched: 32
32 is not found in the dictionary

Result: The above program has been executed successfully


Program 06: Random number generation

Aim: To generate random numbers between 1 to 6 (stimulate a dice)

Program:

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

Sample Input and Output: [To be written on the left hand side of the record note]

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 above program has been executed successfully


Text Files
Program 07: Read a text file line by line and print # after each word

Aim: To read a text file, line by line and display each word separated by ‘#’

Program:

def Line2WordaddHash():
with open('Mystory.txt') as F:
Lines = F.readlines()
myList = []
for i in Lines:
myList = i.split()
for j in myList:
print(j,"#",end= " ")
Line2WordaddHash()

Sample Input and Output: [To be written on the left hand side of the record note]

This # is # my # first # text # file # This # is # my # second # line # India # is # my #


mother # land # I # love # my # country #

Result: The above program has been executed successfully


Program 08: Printing all the lines starting with ‘T’

Aim: To read a text file and print all the lines that are starting with ‘T’ on the screen

Program:

def PrintSpecificLines():
with open('Mystory.txt') as F:
Reader = F.readlines()
for line in Reader:
if line[0] == 'T':
print(line)
PrintSpecificLines()

Sample Input and Output: [To be written on the left hand side of the record note]

This is my first text file

This is my second line

Result: The above program has been executed successfully


Program 09: Counting the number of occurrences of ‘is’ and ‘and ‘ in a text file

Aim: To read a text file and count the number of occurrences of ‘is’ and ‘and’ in that file.

Program:

def Countisand():
with open('Mywordfile.txt','r') as rfile:
Reader = rfile.readlines()
print(Reader)
count = 0
for line in Reader:
words = line.split()
for i in words:
if i == 'is' or i == 'and':
count+=1
print('The total no. of words with is / and = ',count)
Countisand()

Sample Input and Output: [To be written on the left hand side of the record note]

['This is my sample text file program to coun the number of occurrences of is and and present
in this text file.']
The total no. of words with is / and = 4

Result: The above program has been executed successfully


Program 10: Counting vowels, consonants, digits, special characters, lower case & upper
case letters present in a text file.

Aim: 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:

import string
def TextFileCounting():
ucase = 0
lcase = 0
vowels = 0
consonants = 0
digits = 0
special = 0
with open('SampleText.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
if ch.islower():
lcase+=1
elif ch.isdigit():
digits+=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 special characters = ',special)
TextFileCounting()

Sample Input and Output: [To be written on the left hand side of the record note]
No of uppercase alphabets = 7
No of lowercase alphabets = 164
No of digits = 2
No of vowels = 63
No of consonants = 108
No of special characters = 40

Result: The above program has been executed successfully


Program 11: To read a text file and create a new file after adding “ing” to all words ending
with ‘s’ and ‘d’:

Aim: To read a text file and create a new file after adding “ing” to all words ending with ‘s’
and ‘d’

Program:

def Adding_ing():
with open('Mywordfile.txt','r') as rfile:
with open('Mywordfilewith_ing.txt','w') as wfile:
Reader = rfile.readlines()
print(Reader)

for line in Reader:


words = line.split()
for i in words:
if i[-1] == 's' or i[-1] == 'd':
i = i + 'ing'
wfile.write(i)
with open('Mywordfilewith_ing.txt','r') as wfile:
Reader = wfile.readlines()
print(Reader)

Adding_ing()

Sample Input and Output: [To be written on the left hand side of the record note]

['This is my sample text file program to coun the number of occurrances of is and and present
in this text file.']
['Thisingisingmysampletextfileprogramtocounthenumberofoccurrancesingofisingandingandin
gpresentinthisingtextfile.']

Result: The above program has been executed successfully


csv Files
Program 12: Storing and retrieving student’s information using csv file

Aim: To store and retrieve student’s information using csv file.

Program:

import csv
stu = []
def write_csv_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_csv_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_csv_data()
read_csv_data()

Sample Input and Output: [To be written on the left hand side of the record note]

Enter the student name:Kayal


Total marks:475
Do you want to continue y/n: y
Enter the student name:Avinash
Total marks:445
Do you want to continue y/n: n
abc 450 90.0
bcd 455 91.0
cde 460 92.0
def 465 93.0
Senthil 440 88.0
Abi 400 80.0
Harini 415 83.0
Hari 400 80.0
Sundar 425 85.0
Senthil 375 75.0
Abirami 350 70.0
Guna 300 60.0
Abishek 275 55.0
Kayal 475 95.0
Avinash 445 89.0

Result: The above program has been executed successfully


Program 13: Copying the contents of one csv file to another using different delimiter

Aim: To copy the contents of a csv file into another file using different delimiter

Program:

import csv
def copy_csv_data():
with open('InputData01.csv') as F1:
with open('WriteData01.csv','w',newline='') as F2:
Read = csv.reader(F1)
Write = csv.writer(F2,delimiter= '#')
for line in Read:
Write.writerow(line)
def display_copied_data():
with open('WriteData01.csv') as F:
Reader = csv.reader(F)
for Data in Reader:
print(Data)
copy_csv_data()
display_copied_data()

Sample Input and Output: [To be written on the left hand side of the record note]

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

Result: The above program has been executed successfully


Binary Files
Program 14: Search and display using binary file

Aim: To create a binary file to store member no and member name. Given a member no,
display its associated name else display appropriate error message.

Program:

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_display_binary_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('MemberNo not found')
Store_binary_info()
Search_display_binary_info()
Search_display_binary_info()

Sample Input and Output: [To be written on the left hand side of the record note]

Enter the member no: 8002


Enter the name: Sukanya
Do you want to continue y/n :y
Enter the member no: 8003
Enter the name: Archana
Do you want to continue y/n :y
Enter the member no: 8004
Enter the name: Prasath
Do you want to continue y/n :n
Binary File writing is over
Enter the member no to be searched:8003
{'MemberNo': 8003, 'Name': 'Archana'}
Enter the member no to be searched:8008
MemberNo not found

Result: The above program has been executed successfully


Program 15: Menu driven program to write/read/update and append data on to binary file

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

Program:

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_Display_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'] == 'Sundar':
Member['Name'] = 'Sundari'
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. To create and store binary data')
print('2. To read the binary data')
print('3. To update the binary data')
print('4. To append data to the binary file')
print('5. To exit')
ch = int(input('Enter your choice: '))
if ch == 1:
Writing_Binary()
elif ch == 2:
Read_Display_Binary()
elif ch == 3:
Update_Binary()
elif ch == 4:
Append_Binary()
elif ch == 5:
break
Sample Input and Output: [To be written on the left hand side of the record note]

>>> %Run Binary_menu_driven.py


-----------------------
Menu Driven Programming
-----------------------
1. To create and store binary data
2. To read the binary data
3. To update the binary data
4. To append data to the binary file
5. To exit
Enter your choice: 1
Enter the member no: 101
Enter the name: Senthil
Do you want to continue y/n :y
Enter the member no: 102
Enter the name: Arun
Do you want to continue y/n :y
Enter the member no: 103
Enter the name: Dharshini
Do you want to continue y/n :n
Binary File writing is over
-----------------------
Menu Driven Programming
-----------------------
1. To create and store binary data
2. To read the binary data
3. To update the binary data
4. To append data to the binary file
5. To exit
Enter your choice: 4
Enter the member no: 104
Enter the name: Akash
Do you want to continue y/n :y
Enter the member no: 105
Enter the name: Sundar
Do you want to continue y/n :n
Binary File writing is over
-----------------------
Menu Driven Programming
-----------------------
1. To create and store binary data
2. To read the binary data
3. To update the binary data
4. To append data to the binary file
5. To exit
Enter your choice: 2
{'MemberNo': 101, 'Name': 'Senthil'}
{'MemberNo': 102, 'Name': 'Arun'}
{'MemberNo': 103, 'Name': 'Dharshini'}
{'MemberNo': 104, 'Name': 'Akash'}
{'MemberNo': 105, 'Name': 'Sundar'}
Finished reading binary file
-----------------------
Menu Driven Programming
-----------------------
1. To create and store binary data
2. To read the binary data
3. To update the binary data
4. To append data to the binary file
5. To exit
Enter your choice: 3
{'MemberNo': 105, 'Name': 'Sundari'}
-----------------------
Menu Driven Programming
-----------------------
1. To create and store binary data
2. To read the binary data
3. To update the binary data
4. To append data to the binary file
5. To exit
Enter your choice: 5

Result: The above program has been executed successfully

You might also like