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

Contents

USER DEFINED FUNCTIONS 5


PRACTICAL NO. 1. WAP to create a list of 10 elements and perform the
following: 5
a. Reverse the list 5
b. Sort the list 5
c. Print all the elements from 3rd to 8th index 5
d. Add all the elements of the list 5
PRACTICAL NO. 2. Create a UDF (User Defined Function) to calculate
and return the sum of all the multiples of 5 from a list of 10 elements
input by the user. The function should accept the list as the parameter.
6
PRACTICAL NO. 3. WAP using function to display even/odd numbers
from 1 to n. 7
PRACTICAL NO. 4. Write a UDF to check whether a string entered by the
user is a palindrome or not. The function should accept the string as the
parameter and return 0 (False) or 1(True) accordingly. 8
PRACTICAL NO. 5. Write a program to input a number from the user
and the choice to perform operation on the number. Define the functions
as per the following: 9
Choice Operation 9
a. Reverse the number 9
b. Find out if the number is prime or not 9
c. Find the factorial of the number 9
PRACTICAL NO. 6. Write a program to input a string from the user and
perform the following: 10
a. Count the uppercase, lowercase, digits, spaces and special characters
from the string. 10
b. Toggle the string 10
c. Find the occurrence of a particular substring in the main string 10
Page 1 of 62
(display the index of the occurrence) 10
PRACTICAL NO. 7. Write a Python function sin(x, n) to calculate the
value of sin(x) using its Taylor series expansion up to n terms. Compare
the values of sin(x) for different values of n with the correct value. 11
PRACTICAL NO. 8. Write a menu driven program to calculate: Surface
Area, perimeter and volume of a cuboid. 12
PRACTICAL NO. 9. WAP to demonstrate the implementation of scope –
LOCAL, GLOBAL, ENCLOSED and BUILT IN. 13
PRACTICAL NO. 10. WAP to demonstrate the implementation of default
parameters with an example of calculating salary to be paid to a daily
wager where the daily wage and the number of days are passed as
arguments. Assume one day wage as Rs. 450, if the daily wage is missing
and number of days in a month as 26 if number of days are also missing.
14
PRACTICAL NO. 11. WAP to display the output of a function, if the
argument passed is immutable data type. 15
PRACTICAL NO. 12. WAP to display the output of a function, if the
argument passed is mutable data type. 17
PRACTICAL NO. 13. Accept principle amount, rate of interest and time
from the user. Calculate compound interest using a function. The
function should return both compound interest as well as amount thus
demonstrating the concept of function returning multiple values. 18
PRACTICAL NO. 14. Demonstrate the implementation of Generic
Positional parameter/arguments. 19
RANDOM 20
PRACTICAL NO. 15. Write a random number generator program that
generates random numbers between 1 & 6 (simulates a dice). 20
PRACTICAL NO. 16. Lucky seven game. 21
LISTS 23
PRACTICAL NO. 17. Swap the first half of the list with the second half
using a function. 23
PRACTICAL NO. 18. Swap the alternate elements in a list. 23
PRACTICAL NO. 19. WAP to insert item in selected position in a list.24

Page 2 of 62
PRACTICAL NO. 20. Take a sample of 10 phishing e-mails and find the
most common words. 25
TEXT FILE HANDLING 27
PRACTICAL NO. 21. Define a function to read and display the contents
of a text file with each word separated by “#” sign. 27
PRACTICAL NO. 22. WAP to create a user defined function c_count() for
counting the number of characters present in a text file STORY.TXT. 28
PRACTICAL NO. 23. Write a user defined function LCOUNT() in python 
to count the number of lines present in a text file “DATA.TXT”. Also print
the file line by line. 29
PRACTICAL NO. 24. WAP to count the number of alphabets and digits
present in a text file “NOTES.TXT”. 30
PRACTICAL NO. 25. WAP to display only those words which start with
“A” in a text file “XY.TXT”. 31
PRACTICAL NO. 26. Define a function to read a text file and count the
number of words with less than 10 characters. 32
PRACTICAL NO. 27. A text file “Quotes.Txt” has the given data written in
it: 33
Write a user defined function wcount() to display the total number of
words present in the file. 33
PRACTICAL NO. 28. Read a text file “Inform.txt” and display it such that
all cases are toggled. (Uppercase to lower case and vice- versa). 34
PRACTICAL NO. 29. Read a file “inform.txt” line by line and print only
those lines starting with ‘T’ or ‘A’ 35
PRACTICAL NO. 30. WAP to read a random line from a file. 36
PRACTICAL NO. 31. The content of the file ‘myPet.txt’ is given. There is
a typing error in the file. By mistake every ‘c’ or ‘C’ is being typed as ‘f’ or
‘F’. Display the file such that every f is replaced by c and F by C (assuming
there is no genuine use of ‘f’ in the file otherwise. 37
PRACTICAL NO. 32. WAP to count number of vowels present in text file
STORY.TXT. 38
PRACTICAL NO. 33. WAP to count frequency of words in a file. 39

Page 3 of 62
PRACTICAL NO. 34. WAP to remove all the lines which contain the
character ‘a’ from a file and write them in another file. 40
BINARY FILE HANDLING 41
PRACTICAL NO. 35. Create a data file to store the details of books
having book_code, name, author and price. Define a function to read the
file and display the details of the books written by ” Sumita Arora”. 41
PRACTICAL NO. 36. WAP to get rnos, names and marks of the students
of a class and store them in a binary file called “Marks.dat”. 42
Also, define a function to update the records of those students whose
roll number is entered by the user. 42
PRACTICAL NO. 37. Write a menu driven program which should be able
to read, write, search, delete or modify data from a binary file (String
type). 43
CSV FILE HANDLING 48
PRACTICAL NO. 38. WAP to insert list data in CSV file. 48
PRACTICAL NO. 39. WAP to read data from a CSV file. 49
PRACTICAL NO. 40. WAP to write dictionary data in CSV file. 50
PRACTICAL NO. 41. WAP to write nested list data in CSV file. 51
PRACTICAL NO. 42. Create a csv file to store the details of flights
including the flight_name, destination and fare. Define a function to
display the details of the flights whose fare is above 15000. 52
PRACTICAL NO. 43. CSV Dummy Project – bookshop.csv (Add, delete,
traverse and update a record) 53

Page 4 of 62
USER DEFINED FUNCTIONS
PRACTICAL NO. 1. WAP to create a list of 10 elements
and perform the following:
a. Reverse the list
b. Sort the list
c. Print all the elements from 3rd to 8th index
d. Add all the elements of the list

Output:

Page 5 of 62
PRACTICAL NO. 2. Create a UDF (User Defined
Function) to calculate and return the sum of all the
multiples of 5 from a list of 10 elements input by the
user. The function should accept the list as the
parameter.

Output:

Page 6 of 62
PRACTICAL NO. 3. WAP using function to display
even/odd numbers from 1 to n.

def even(a):
for i in range(2,a+1,2):
print(i)

def odd(a):
for i in range(1,a+1,2):
print(i)

n=int(input('Enter n:'))
choice=input('even(e) or odd(o):')

if choice in ['e',’E’]:
even(n)
elif choice in ['o',’O’]:
odd(n)
else:
print('invalid choice')

Output:

Page 7 of 62
PRACTICAL NO. 4. Write a UDF to check whether a
string entered by the user is a palindrome or not.
The function should accept the string as the
parameter and return 0 (False) or 1(True)
accordingly.

Output:

Page 8 of 62
PRACTICAL NO. 5. Write a program to input a number
from the user and the choice to perform operation
on the number. Define the functions as per the
following:
Choice Operation
a. Reverse the number
b. Find out if the number is prime or not
c. Find the factorial of the number

Output:

Page 9 of 62
PRACTICAL NO. 6. Write a program to input a string
from the user and perform the following:
a. Count the uppercase, lowercase, digits, spaces and
special characters from the string.
b. Toggle the string
c. Find the occurrence of a particular substring in
the main string
(display the index of the occurrence)

Page 10 of 62
PRACTICAL NO. 7. Write a Python function sin(x, n) to
calculate the value of sin(x) using its Taylor series
expansion up to n terms. Compare the values of
sin(x) for different values of n with the correct
value.

def sin(x,n):
sum=0
for i in range(n):
fact=1
for j in range(1,2*i+2):
fact*=j
t=(-1)**i*(x**(2*i+1))/fact
sum+=t
print('n=',n)
print('Sin',x,’:’,round(sum,6),sep=’’)

for i in range(3,6):
sin(2,i)

print('Actual value of sin(2) upto 6 decimal places is 0.909297')

Output:

Page 11 of 62
Page 12 of 62
PRACTICAL NO. 8. Write a menu driven program to
calculate: Surface Area, perimeter and volume of a
cuboid.

def area(l,b,h):
print('Area:',2*(l*b+l*h+b*h))

def peri(l,b,h):
print('Perimeter:',4*(l+b+h))

def vol(l,b,h):
print('Volume:',l*b*h)

l=float(input('Enter length:'))
b=float(input('Enter breadth:'))
h=float(input('Enter height:'))
print('1:Surface area\n2:Perimeter\n3:Volume')
choice=int(input('Enter choice:'))
if choice==1:
area(l,b,h)
elif choice==2:
peri(l,b,h)
elif choice==3:
vol(l,b,h)
else:
print('Invalid choice')

Output:

Page 13 of 62
PRACTICAL NO. 9. WAP to demonstrate the
implementation of scope – LOCAL, GLOBAL,
ENCLOSED and BUILT IN.

'''
LEGB rule: Priority of scopes
4 scopes are-

1. Built In- Contains names such as keywords, functions, exceptions & other
attributes that are built into python.
Scope- Visible in all python programs.

2. Global- Defined outside any function in a python program.


Scope- Visible throughout till program is in execution.

3. Local- Contains the names that we define inside the function.


Scope- Visible only inside the function.

4. Enclosed- Only exists for nested functions.


Scope- If local scope is inner or nested function, then enclosing scope is
scope of outer or enclosing function.
'''
# print() - Built in
def f1():
x=20 #Enclosing
print(x)
def f2():
x=30 #Local
print(x)
f2()

x=10 #Global
f1()
print(x)
Output:

Page 14 of 62
PRACTICAL NO. 10. WAP to demonstrate the
implementation of default parameters with an
example of calculating salary to be paid to a daily
wager where the daily wage and the number of days
are passed as arguments. Assume one day wage as
Rs. 450, if the daily wage is missing and number of
days in a month as 26 if number of days are also
missing.

def pay(days=26,wage=450):
sal=days*wage
print('Salary is',sal)

pay(24,550) #if both given, no default value is taken


pay(24) #if wage not given, it takes default value
pay() #if both not given, both take default values

OR

def pay(wage=450,days=26):
sal=days*wage
print('Salary is',sal)

pay(550,24) #if both given, no default value is taken


pay(550) #if days not given, it takes default value
pay() #if both not given, both take default values

Page 15 of 62
PRACTICAL NO. 11. WAP to display the output of a
function, if the argument passed is immutable data
type.

#string
def func(str1):
str1='Hi '+str1
print(str1)
print('Within function:',str1)

str1=input('Enter a string:')
func(str1)
print('After function call:',str1)

#integer
def calAdd(a,b):
a+=b
print('Within function a is',a)

a=int(input('Enter a:'))
b=int(input('Enter b:'))
calAdd(a,b)
print('After function call, a=',a,',b=',b)

Page 16 of 62
#tuple
def combo(x,y):
x+=y
print('Within function:',x)

t1=(80,70)
t2=('Hi','Hello')
combo(t1,t2)
print('t1 is',t1)
combo(t2,t1)
print('t2 is',t2)

PRACTICAL NO. 12. WAP to display the output of a


function, if the argument passed is mutable data
type.

Page 17 of 62
#list
def func(L1):
L1.append(8)
print('Within function:\n',L1)

L1=eval(input('Enter list:'))
func(L1)
print('After function call:\n',L1)

#dictionary
def func(dict1):
dict1['age']=16
print('Within function:\n',dict1)

dict1={'Name':'Prachi','Height':5.0}
func(dict1)
print('After function call:\n',dict1)

PRACTICAL NO. 13. Accept principle amount, rate


of interest and time from the user. Calculate
compound interest using a function. The function
should return both compound interest as well as
amount thus demonstrating the concept of function
returning multiple values.

Page 18 of 62
def compound(p,r,t):
a=p*(1 + r/100)**t
i=a-p
return (i,a)

p=int(input('Enter principle amount(Rs.):'))


r=float(input('Enter rate of interest(%):'))
t=int(input('Enter time period(Yrs):'))

(intr,amt)=compound(p,r,t)
print('Compound interest:',round(intr,2))
print('Amount:',round(amt,2))

Page 19 of 62
PRACTICAL NO. 14. Demonstrate the implementation
of Generic Positional parameter/arguments.

def cal(*N):
p=1
for i in N:
p*=i
print(i,end=' ')
print()
return(p)

x=cal(5)
print('Product:',x)

x=cal(5,15)
print('Product:',x)

x=cal(5,15,25)
print('Product:',x)

Page 20 of 62
RANDOM
PRACTICAL NO. 15. Write a random number
generator program that generates random numbers
between 1 & 6 (simulates a dice).

import random
while True:
choice=input('Want to roll the dice?(y/n):')

if choice.lower()=='n':
print('Terminating...')
break

elif choice.lower() not in ['y','n']:


print('Invalid choice')

else:
print(random.randint(1,6))

Page 21 of 62
PRACTICAL NO. 16. Lucky seven game.

import random
score=0
attempts=0
print('Maximium 5 attempts')
while attempts<5:
choice=input('Want to start?(y/n):')

if choice.lower()=='n':
break
elif choice.lower() not in ['y','n']:
print('Invalid choice')
else:
attempts+=1
sum=0
print('Numbers generated are',end=' ')
for i in range(3):
num=random.randint(1,6)
sum+=num
print(num,end=' ')
print()

if sum==7:
print('You got sum as',sum,'...
increasing score by 10')
score+=10

elif sum<7:
print('You got sum as',sum,'...
increasing score by 7')
score+=7

else:
print('You got sum as',sum,'...
increasing score by 4')
score+=4
print('','Terminating...',sep='\n')

Page 22 of 62
print('Your score is',score)

Page 23 of 62
LISTS

PRACTICAL NO. 17. Swap the first half of the list with
the second half using a function.

def swap(a):
n=len(a)
for i in range(n//2):
a[i],a[i+n//2]=a[i+n//2],a[i]
print('After swapping...',a)

a=[11,12,13,14,15,16]
swap(a)

PRACTICAL NO. 18. Swap the alternate elements in a


list.

def swap(a):
n=len(a)
for i in range(0,n,2):
a[i],a[i+1]=a[i+1],a[i]
print('After swapping...',a)

a=[11,12,13,14,15,16]
swap(a)

Page 24 of 62
PRACTICAL NO. 19. WAP to insert item in selected
position in a list.

L=[10,20,30,50]
print('List is',L)
while True:
choice=input('Want to insert a number?(y/n):')
if choice.lower()=='n':
print('Terminating...')
break

elif choice.lower() not in ['y','n']:


print('Invalid choice')
else:
num=int(input('Enter number to be inserted:'))
pos=int(input('Enter index number:'))
if pos<0 or pos>=len(L):
print('Invalid index')
else:
L.insert(pos,num)
print(L)

Page 25 of 62
PRACTICAL NO. 20. Take a sample of 10 phishing
e-mails and find the most common words.

import collections
file=open('phishing.txt','r')
a=file.read()
a.lower()
cont=a.split()
d={}

for i in cont:
i.replace(".","")
i.replace(",","")
i.replace("'","")
i.replace(":","")
i.replace("!","")
i.replace("&","")
i.replace("\"","")

for j in cont:
if j not in d:
freq=cont.count(j)
d[j]=freq

num=int(input('Number of common words:'))


words=collections.Counter(d)

for a,b in words.most_common(num):


print(a,':',b)
file.close()

Page 26 of 62
Page 27 of 62
TEXT FILE HANDLING

PRACTICAL NO. 21. Define a function to read and


display the contents of a text file with each word
separated by “#” sign.

Output:

Page 28 of 62
PRACTICAL NO. 22. WAP to create a user defined
function c_count() for counting the number of
characters present in a text file STORY.TXT.
def c_count(s):
print('No. of characters are:',len(s))

file=open('STORY.txt','r')
s=file.read()
c_count(s)
file.close()

Page 29 of 62
PRACTICAL NO. 23. Write a user defined function
LCOUNT() in python  to count the number of lines
present in a text file “DATA.TXT”. Also print the file line
by line.
def LCOUNT():
file=open('DATA.txt','r')
s=file.readlines()
print('No. of lines:',len(s))
for i in s:
print(i)

LCOUNT()
file.close()

Page 30 of 62
PRACTICAL NO. 24. WAP to count the number of
alphabets and digits present in a text file “NOTES.TXT”.
def COUNT():
file=open('NOTES.txt','r')
s=file.read()
alpha=0
dig=0

for i in s:
if (i>='a' and i<='z') or (i>='A' and i<='Z'):
alpha+=1

if i in ('1','2','3','4','5','6','7','8','9'):
dig+=1

print('alphabets:',alpha,' and digits:',dig)

COUNT()
file.close()

Page 31 of 62
PRACTICAL NO. 25. WAP to display only those
words which start with “A” in a text file “XY.TXT”.

file=open('XY.txt','r')
s=file.read()
a=s.split()

for i in a:
if i[0]=='a' or i[0]=='A':
print(i)

file.close()

Page 32 of 62
PRACTICAL NO. 26. Define a function to read a text
file and count the number of words with less than 10
characters.

Output:

Page 33 of 62
PRACTICAL NO. 27. A text file “Quotes.Txt” has the
given data written in it: 

Living a life you can be proud of Doing your best Spending your
time with people and activities that are important to you Standing
up for things that are right even when it’s hard Becoming the best
version of you 
 
Write a user defined function wcount() to display the
total number of words present in the file. 
def wcount():
file=open('Quotes.txt','r')
s=file.read()
a=s.split()
print(len(a))

wcount()
file.close()

Page 34 of 62
PRACTICAL NO. 28. Read a text file “Inform.txt” and
display it such that all cases are toggled. (Uppercase to
lower case and vice- versa).
 
file=open('Inform.txt','r')
s=file.read()

for i in s:
if i>='a' and i<='z':
print(chr(ord(i)-32),end='')

elif i>='A' and i<='Z':


print(chr(ord(i)+32),end='')

else:
print(i,end='')

file.close()

Page 35 of 62
PRACTICAL NO. 29. Read a file “inform.txt” line by line
and print only those lines starting with ‘T’ or ‘A’
file=open('INFORM2.txt','r')
s=file.readlines()
for i in s:
if i[0] in ('T','A'):
print(i)
file.close()

Page 36 of 62
PRACTICAL NO. 30. WAP to read a random line from a
file.
import random
file=open('INFORM2.txt','r')
s=file.readlines()
a=random.randint(0,len(s)-1)
print(s[a])
file.close()

Page 37 of 62
PRACTICAL NO. 31. The content of the file ‘myPet.txt’
is given. There is a typing error in the file. By mistake
every ‘c’ or ‘C’ is being typed as ‘f’ or ‘F’. Display the file
such that every f is replaced by c and F by C (assuming
there is no genuine use of ‘f’ in the file otherwise.

This is my fute Fat. I fare a lot about my fat. I fall it Findrella.

The expected output is:


This is my cute Cat. I care a lot about my cat. I call her Cindrella

Output:

Page 38 of 62
PRACTICAL NO. 32. WAP to count number of vowels
present in text file STORY.TXT.

Output:

Page 39 of 62
PRACTICAL NO. 33. WAP to count frequency of words
in a file.

file=open('Count.txt','r')
cont=file.read()
a=cont.split()
d={}
for word in a:
if word not in d:
num=a.count(word)
d[word]=num

for i in d:
print(i,':',d[i])
flie.close()

Page 40 of 62
PRACTICAL NO. 34. WAP to remove all the lines which
contain the character ‘a’ from a file and write them in
another file.

Page 41 of 62
BINARY FILE HANDLING
PRACTICAL NO. 35. Create a data file to store the
details of books having book_code, name, author and
price. Define a function to read the file and display the
details of the books written by ” Sumita Arora”.

Page 42 of 62
PRACTICAL NO. 36. WAP to get rnos, names and
marks of the students of a class and store them in a
binary file called “Marks.dat”.
Also, define a function to update the records of those
students whose roll number is entered by the user.
import pickle
def writefile():
    l=[]
    ch="y"
    file=open("Marks.dat","wb")
    while ch=="y":
            rollno=int(input("enter roll no : "))
            name=input("enter name : ")
            marks=int(input("enter marks : "))
            re=[rollno,name,marks]
            pickle.dump(re,file)
            ch=input("do you want to add more records")
    file.close()
def display():
    file=open("Marks.dat","rb")
    try:
        while True:
            rec=pickle.load(file)
            print(rec)
    except EOFError:
        pass
    file.close()
            
def update():
    file=open("Marks.dat","rb+")    
    found=0
    a=[]
    r=int(input("enter roll no. for update "))
    try:
        while True:
            loc=file.tell()
            rec=pickle.load(file)
            if r==rec[0]:
                found=1
                print(rec)
                file.seek(loc,0)
                
                name=input("update correct name : ")

Page 43 of 62
                marks=int(input("update correct marks : "))
                a=[r,name,marks]
                pickle.dump(a,file)
    except EOFError:
        print('File processed....')
    file.close()
            
    if(found==0):
        print("\n \n rollno.not found \n \n ")
    elif(found==1):
        print("Updated")

writefile()
display() 
update()
display()

Output:

Page 44 of 62
PRACTICAL NO. 37. Write a menu driven program
which should be able to read, write, search, delete or
modify data from a binary file (String type).

import pickle
import os

def binread():
try:
fr=open('ministr.dat','rb')
while True:
file=pickle.load(fr)
print(file)
except EOFError:
fr.close()
pass
except FileNotFoundError:
print('File does not exist')

def binwrite():
fw=open('ministr.dat','wb')
cont=input('Enter content to be written in file:')
pickle.dump(cont,fw)
fw.close()
print('written successfully')

def binappend():
fa=open('ministr.dat','ab')
new_cont=input('Enter content to be added in file:')
pickle.dump(new_cont,fa)
fa.close()
print('added successfully')

def strsearch():
fr=open('ministr.dat','rb')
val=input('Enter record to be searched:')
pos=0

Page 45 of 62
try:
while True:
cont=pickle.load(fr)
if cont==val:
print('Record Found at position',pos)
break
pos+=1
except EOFError:
print('Record not found')
fr.close()

def strdelete():
fr=open('ministr.dat','rb')
fw=open('temp.dat','wb')
val=input('Enter record to be deleted:')
found=0
try:
while True:
cont=pickle.load(fr)
if cont!=val:
pickle.dump(cont,fw)
else:
found=1
print('Record deleted')
except EOFError:
pass

if found==0:
print('Record not found')
fr.close()
fw.close()
os.remove('ministr.dat')
os.rename('temp.dat','ministr.dat')

def strupdate():
fr=open('ministr.dat','rb')
fw=open('temp.dat','wb')
val=input('Enter record to be updated:')

Page 46 of 62
found=0

try:
while True:
cont=pickle.load(fr)
if cont!=val:
pickle.dump(cont,fw)
else:
found=1
new_val=input('Enter new record:')
pickle.dump(new_val,fw)
print('Record updated')
except EOFError:
pass

if found==0:
print('Record not found')
fr.close()
fw.close()
os.remove('ministr.dat')
os.rename('temp.dat','ministr.dat')

while True:
os.system('cls')
print('Menu\n1:Read\n2:Write\n3:Append\n4:Record search\n5:Record
delete\n6:Record update')
choice=int(input('Enter choice(1 or 2 or 3 or 4 or 5 or 6):'))

if choice==1:
binread()
elif choice==2:
binwrite()
elif choice==3:
binappend()
elif choice==4:
strsearch()
elif choice==5:
strdelete()

Page 47 of 62
elif choice==6:
strupdate()
else:
print('Invalid choice')
input('Press enter to continue')

re=input('Want to try again(y or n):')


if re.lower()=='n':
print('Terminating Program...')
break
elif re.lower() not in ['y','n']:
print('Invalid choice')
input('Press enter to continue')

Page 48 of 62
Page 49 of 62
CSV FILE HANDLING

PRACTICAL NO. 38. WAP to insert list data in CSV file.

import csv
def ADD():
csv_w=open('prac1.csv','a',newline='')
obj=csv.writer(csv_w)
rno=int(input('Enter rno:'))
name=input('Enter name:')
marks=float(input('Enter marks:'))
record=[rno,name,marks]
obj.writerow(record)
print('Added successfully')
del record
csv_w.close()

num=int(input('Number of records to be entered:'))


for i in range(num):
ADD()

Page 50 of 62
Page 51 of 62
PRACTICAL NO. 39. WAP to read data from a CSV file.

import csv

try:
csv_r=open('prac1.csv','r')
obj=csv.reader(csv_r)
print('Rno\tName\t\t\tMarks')
print('-----------------------------')
for row in obj:
if row:
print(row[0],'\t',row[1],'\t\t\t',row[2],sep='')
else:
print('No record found')

del obj
csv_r.close()

except FileNotFoundError:
print('file doesnot exists')

Page 52 of 62
PRACTICAL NO. 40. WAP to write dictionary data in
CSV file.

import csv
def ADD():
csv_w=open('prac2.csv','a',newline='')
obj=csv.writer(csv_w)
record=eval(input('Enter dictionary to be written:'))

for key,value in record.items():


obj.writerow([key,value])

print('Added successfully')
del record
csv_w.close()

num=int(input('Number of records to be entered:'))


for i in range(num):
ADD()

Page 53 of 62
PRACTICAL NO. 41. WAP to write nested list data in
CSV file.

import csv
csv_w=open('prac3.csv','a',newline='')
obj=csv.writer(csv_w)
record=[['Priya',95] , ['Neha',82]]

for i in record:
obj.writerow(i)

print('Added successfully')
del record
csv_w.close()

Page 54 of 62
PRACTICAL NO. 42. Create a csv file to store the
details of flights including the flight_name, destination
and fare. Define a function to display the details of the
flights whose fare is above 15000.

Output:

Page 55 of 62
PRACTICAL NO. 43. CSV Dummy Project –
bookshop.csv (Add, delete, traverse and update a
record)

import csv
import os

def ADD():
csv_w=open('bookshop.csv','a',newline='')
obj=csv.writer(csv_w)
code=input('Enter book code:')
name=input('Enter book name:')
price=int(input('Enter price:'))
record=[code,name,price]
obj.writerow(record)
print('Added successfully')
del record
csv_w.close()
def READ():
try:
csv_r=open('bookshop.csv','r')
obj=csv.reader(csv_r)
print('Code\tName\t\t\tPrice')
print('--------------------------------------')
for row in obj:
if row:
Page 56 of 62
print(row[0],'\t',row[1],'\t\t',row[2])
else:
print('No record found')

del obj
csv_r.close()

except FileNotFoundError:
print('File does not exist')

def DELETE():
found=0
code=input('Enter book code to be deleted:')
try:
csv_r=open('bookshop.csv','r')
csv_w=open('temp.csv','w',newline='')
objr=csv.reader(csv_r)
objw=csv.writer(csv_w)
for row in objr:
if row[0]==code:
found=1
else:
objw.writerow(row)

del objr
del objw
csv_r.close()
csv_w.close()

except:
print('Unexpected error')

os.remove('bookshop.csv')
os.rename('temp.csv','bookshop.csv')

if found==0:
print('No such record exists')

Page 57 of 62
else:
print('Deleted successfully')

def UPDATE():
found=0
code=input('Enter book code to be updated:')
try:
csv_r=open('bookshop.csv','r')
csv_w=open('temp.csv','w',newline='')
objr=csv.reader(csv_r)
objw=csv.writer(csv_w)
for row in objr:
if row[0]==code:
found=1
name=input('Enter new book name:')
price=int(input('Enter new price:'))
record=[code,name,price]
objw.writerow(record)

else:
objw.writerow(row)

del objr
del objw
csv_r.close()
csv_w.close()

except:
print('Unexpected error')

os.remove('bookshop.csv')
os.rename('temp.csv','bookshop.csv')

if found==0:
print('No such record exists')

else:

Page 58 of 62
print('Udated successfully')

def ADMIN(end):

while True:
os.system('cls')
print('Administrator account')
print('Menu\n1.Add\n2.Read\n3.Update\n4.Delete\n5.Switch
account\n6.Exit')
choice_ad=int(input('Enter choice(1 to 6):'))
if choice_ad==1:
ADD()
elif choice_ad==2:
READ()
elif choice_ad==3:
UPDATE()
elif choice_ad==4:
DELETE()
elif choice_ad==5:
break
elif choice_ad==6:
input('Press enter to exit')
end=[1]
return end
break

else:
print('Invalid choice\n')
input('Press enter to continue')

def USER(end):

while True:
os.system('cls')
print('User account')
print('Menu\n1.Add\n2.Read\n3.Switch account\n4.Exit')

Page 59 of 62
choice_us=int(input('Enter choice(1 to 4):'))
if choice_us==1:
ADD()
elif choice_us==2:
READ()
elif choice_us==3:
break
elif choice_us==4:
input('Press enter to exit')
end=[1]
return end
break
else:
print('Invalid choice\n')
input('Press enter to continue')

def ACCOUNT():
end=[]
while True:
os.system('cls')
print('1.Admin\n2.User')
acc=int(input('Choose account(1 or 2):'))

if acc==1:
end=ADMIN(end)

elif acc==2:
end=USER(end)

else:
print('Invalid choice\n')
input('Press enter to continue')

if end:
break

ACCOUNT()

Page 60 of 62
Page 61 of 62
Page 62 of 62

You might also like