Professional Documents
Culture Documents
Ex. No. 1
Question :
Write a python program to print Fibonacci series using
function
Aim :
To print Fibonacci series using function
Source code:
def fibonacci(n):
first_term=-1
second_term=1
for i in range(n):
third_term=first_term+second_term
print(third_term,end=' ')
first_term=second_term
second_term=third_term
print("Fibonacci series")
n=int(input("Enter the number of terms you want to
print"))
fibonacci(n)
Result:
The above program has been executed successfully
PALINDROME
Ex. No. 2
Question
Write a program to check whether the string is
palindrome or not.
Aim:
To check whether the string is palindrome or not.
Source code
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("Check Palindrome")
mystring=input("Enter a string: ")
mylength=len(mystring)
palindrome(mylength)
Result:
The above program has been executed
successfully
PRINTING THE LARGEST AND SMALLEST COUNTRY NAME IN A LIST
Ex. No. 3
Question
Write a python program to print the largest and smallest country name
in a given list
Aim:
To create a list with different country names and print the smallest
country
Source code
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)
Result:
The above program has been executed successfully
MENU DRIVEN PROGRAM TO CALCULATE AREA OF DIFFERENT SHAPES
Ex. No. 4
Question :
Write a python program to calculate area of different shapes using menu
driven programs
Aim:
To develop a menu driven program to calculate the area of different shapes
using functions Source code:
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 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)
Result:
The above program has been executed successfully
SEARCH AND DISPLAY USING DICTIONARY
Ex. No. 5
Question
Write a python program to store roll number and name of 5
students and search student name through roll no.
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 error
message
Source code:
mydict={ }
def inputdictionary():
for i in range(5):
rno=int(input("Enter the roll no :"))
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 Roll number to be searched : " ))
search(n)
Result:
The above program has been executed successfully
RANDOM NUMBER GENERATION
Ex.No. 6
Question
Write a python program to generate random numbers between 1 to 6
(simulates a dice)
Aim
To generate random numbers between 1 to 6
Source code
import random
Guess=True
while Guess:
n=random.randint(1,6)
userinput=int(input("Enter a number between 1 t0 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
Result:
The above result has been executed successfully.
READ A TEXT FILE LINE AND PRINT # AFTER EACH WORD
Ex.No.7
Question
Write a python program to read a text file line by line and display each word
separated by ‘#’.
Aim:
To read a text file line by line and display each word separated by ‘#’.
Source code:
def add():
with open('Mystory.txt') as f:
lines=f.readlines()
Mylist=[]
for i in lines:
Mylist=i.split()
for j in Mylist:
print(j,"#",end =" ")
add()
Result:
The above result has been executed successfully.
PRINTING ALL THE LINES STARING WITH ‘T’
Ex.No.8
Question
Write a python program to read a text file and print all the lines that are
starting with ‘T’ on the screen.
Aim
To read a text file and print all the lines that are starting with
‘T’ on the screen.
Source code
def print_lines():
with open("Mystory.txt") as f:
Reader=f.readlines()
for line in Reader:
if line[0]=='T':
print(line)
print_lines()
Result:
The above result has been executed successfully.
COUNING THE NUMBER OF OCCURENCES OF ‘IS’ AND ‘AND ‘ IN A TEXT FILE
Ex.No. 9
Question
Write a python program to read a text file and count the number of
occurrences of ‘is’ and ‘and’ in that file
Aim
To read a text file and count the number of occurrences of ‘is’ and ‘and’
in that file
Source code
def count_word():
with open('Mystory.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) count_word()
Result:
The above result has been executed successfully.
COUNTING VOWELS, CONSANANTS, DIGITS, SPECIAL, CHARACTERS, LOWER CASE &
UPPDER CASE LETTERS IN A TEXT FILE
Ex.No. 10
Question
Write a python program to count the number of vowels, consonants digits, special
characters , lower case and upper case letters in a text files
Aim
To count the number of vowels, consonants digits, special characters ,
lower case and upper case letters in a text files
Source code
import string
def text_count():
ucase=lcase=vowels=consonants=digits=special=0
with open('Mystory.txt') as rtfile:
read =rtfile.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)
text_count()
Result:
The above result has been executed successfully.
WRITE A PROGRAM THAT READS A TEXT FILE AND CREATE A NEW FILE AFTER
ADDING "ING" TO ALL WORDS ENDING WITH "T", "P", "D".
EX.No. 11
Question
write a python program that reads a text file and create a new file after adding "ing"
to all words ending with "t", "p", "d".
Aim
To reads a text file and create a new file after adding "ing" to all words ending with
"t", "p",
"d".
Source code:
x=open("f1.txt","r")
y=open("f2.txt","w")
x1=x.readlines()
for i in x1:
l=""
for j in i :
if j[-1]=="t" or j[-1]=="p" or j[-
1]=="d": l+=i +"ing"
else:
l+=i
y.write(l)
x.close()
y.close()
with open("f2.txt","r") as wf:
print(wf.read())
Result:
The above program has been executed successfully
STORING AND RETRIEVING STUDENT’S INFORMATION USING
CSV FILE
Ex.No.12
Question
Write a python program to storing and retrieving student’s
information using csv file
Aim
To storing and retrieving student’s information using
csv file
Source code:
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 u want to continue y/n :')
def read_csv_data():
with open('Inputdata.csv','r')as F:
reader=csv.reader(F)
print("Stu_Name \t Total Mark \t Average")
for data in reader:
print(data[0],'\t\t',int(data[1]),'\t\t',int(data[1])/5)
write_csv_data()
read_csv_data()
Result:
The above program has been executed successfully
COPYNING THE CONTENTS OF ONE CSV FILE TO ANOTHER USING
DIFFERENT DELIMITER
EX. NO 13
Question
Write a python program to copying the contents of one csv
file to another using different delimiter
Aim
To copying the contents of one csv file to another using
different delimiter
Source code:
import csv
def copy_csv_data():
with open('Inputdata.csv')as F1:
with open('write_data_01.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('Write_data_01.csv')as F:
reader=csv.reader (F)
for data in reader:
print(data)
copy_csv_data()
display_copied_data()
Result:
The above program has been executed successfully
SEARCH AND DISPLAY USING BINARY FILE
EX.NO 14
Question
Write a python program to create a binary file to store member no. and
member name. Read 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. Read member
no and 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['Member No']= Mno
Member['Name']= Name
pickle.dump(Member , wbfile)
ch= input('Do you want to continue y/n')
if ch=='n':
print ('Binary file wariting 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['Member No']== Mno:
print(Member)
break
except EOFError:
print ('member no not found')
store_binary_info()
search_display_binary_info()
search_display_binary_info()
Result:
The above program has been executed successfully
MENU DRIVEN PROGRAM TO WRITE /READ/UPDATE/APPEND DATA ON TO
A BINARY FILE
EX. NO.15
Question
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
import pickle
member={}
def w_bin():
with open('Membr.dat','wb')as wbfile:
while True:
m=int(input("Enter the member no:"))
name=input('Enter the name:')
member['MemberNo']=m
member['Name']=name
pickle.dump(member,wbfile)
ch=input('Do you want to contine y/n:') if
ch=='n':
print('Binary file writing is over')
break
def read_bin():
with open('member.dat','rb') as rrfile:
try:
while True:
member=pickle.load(rrfile)
print(member)
except EOFError:
rrfile.close()
def update_bin():
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 succesfully")
def append_Bin():
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 yu 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 binary data')
print('3.To update binary data')
print('4.To append data to the binary file')
print('5.To exit')
ch=int(input("Enter your choice"))
if ch==1:
w_bin()
elif ch==2:
read_bin()
elif ch==3:
update_bin()
elif ch==4:
append_Bin()
elif ch==5:
break
Result:
The above program has been executed
successfully
STACK OPERATION
EX.NO.16
Question
Write a program to implement a stack using a list
data structure.
Aim
To implement the stack operation using a list
data structure.
Program
stack=[]
def view():
for x in range(len(stack)):
print(stack[x])
def push():
item=int(input("Enter integer
value"))
stack.append(item)
def pop():
if(stack==[]):
print("Stack is empty")
else:
item=stack.pop(-1)
print("Deleted
element :",item)
def peek():
item=stack[-1]
print("Peeked
element :",item)
print("Stack operation")
print("***************")
print("1.Push")
print("2.View")
print("3.Pop")
print("4.Peek")
print("5.Exit")
while True:
choice=int(input("Enter your
choice"))
if choice==1:
push()
elif choice==2:
view()
elif choice==3:
pop()
elif choice==4:
peek()
elif choice==5:
break
else:
print("Wrong choice")
Result:
The above program has been executed
successfully
Ex. No 17
MYSQL Command - Exercise I
STATIONARY AND CONSUMER
Aim To create two table for stationary and consumer and execute the given
commands using MYSQL
Table : Stationary
S_ID STATIONARY_NA COMPANY PRICE
DP01 Dot pen ABC 10
PLO2 Pencil XYZ 6
ERO5 Eraser XYZ 7
PL01 Pencil CAM 5
GP02 Gel Pen ABC 15
Table: Consumer
Table : ITEM
TABLE : DOCTOR
ID NAME DEPT SEX EXPERIENCE
101 John ENT M 12
104 SMITH ORTHOPEDIC M 5
107 GEORGE CARDIOLOGY M 10
114 LARA SKIN F 3
109 K GEORGE MEDICINE F 9
105 JOHNSON ORTHOPEDIC M 10
117 LUCY ENT F 3
111 BILL MEDICINE M 12
130 MORPHY ORTHOPEDIC M 15
TABLE : SALARY
TABLE: COMPANY
CID NAME CITY PRODUCT NAME
111 SONY DELHI TV
222 NOKIA MUMBAI MOBILE
333 ONIDA DELHI TV
444 SONY MUMBAU MOBILE
555 BLACK BERRY MADRAS MOBILE
666 DELL DELHI LAPTOP
TABLE : CUSTOMER
TABLE : TEACHER
Source code
Result
The above program has been executed and verified successfully.
Ex.no 23
INTEGRATE PYTHON WITH MYSQL – COUNTING RECORDS FROM TABLE
AIM:
To integrate MSQL with python by importing the MYSQL module and extracting data
from result set
SOURCE CODE:
Result
The above program has been executed and verified successfully.
Ex.no 24
INTEGRATE PYTHON WITH MYSQL – SEARCHING A RECORD FROM TABLE
AIM:
To integrate MSQL with python by importing the MYSQL module to search an
employee using Employee Number, if it is present in table display the record
SOURCE CODE:
Result
The above program has been executed and verified successfully.
Ex.no 25
INTEGRATE PYTHON WITH MYSQL – DELETING A RECORD FROM TABLE
AIM:
To integrate MSQL with python by importing the MYSQL module to search a
student using roll number, if it is present in table delete the record
SOURCE CODE
import mysql.connector as mysqltor
mycon=mysqltor.connect(host='localhost',
user='root' ,passwd='root', database='Student')
if mycon.is_connected()==False:
print("Error connecting to Mysql database")
cur=mycon.cursor()
cur.execute("select * from stu_per")
data=cur.fetchall()
for row in data:
print(row)
print()
sno=int(input("Enter Student No. Which you want to delete"))
delete=0
for row in data:
if row[0]==sno:
delete=1
cur.execute("delete from stu_per where stu_no={}".format(sno))
mycon.commit()
print()
if delete==1:
print("Your Record deleted successfully")
else:
print("Invalid Student No")
print()
cur.execute("select * from stu_per")
data=cur.fetchall()
for row in data:
print(row)
mycon.close()
Result
The above program has been executed and verified successfully.