Wednesday, 9 April 2025

GRADE 12 : PRACTICAL 9 : BINARY FILES

 '''Write a program to create a binary file Course.dat

for DIIT training centre to store course information of

all the computer language courses held at their institute.

Each record should be of the form :

[ course_id, course_name, duration(in months), fee].

The program should include the following functionalities:

i) Append new course records to the binary file.

ii) Display all course records from the binary file.

iii) Search for a course by course_id and display its

details, otherwise display an error.

iv) Calculate the average fees of the courses at DIIT

centre.

v) Increase the fees of each course by 10%'''

import pickle

def menu():

    while True :

        ch=int(input("""MENU :

1) ADD record

2) DISPLAY records

3) SEARCH for record

4) CALCULATE the average fees of the course

5) UPDATE record

6) EXIT

YOUR CHOICE : """))

        if ch==1:

            add()

        elif ch==2:

            display()

        elif ch==3:

            search()

        elif ch==4:

            calculate()

        elif ch==5:

            update()

        else:

            break


def add():

    with open('course.dat','ab') as f:

        n=int(input("Enter number of records : "))

        for i in range(n):

            c_id=int(input("Enter course id : "))

            c_name=input("Enter course name : ")

            duration=int(input("Enter the course duration(months) : "))

            fee=int(input("Enter the fees : "))

            rec=[c_id,c_name,duration,fee]

            pickle.dump(rec,f)


def display():

    try:

        with open('course.dat','rb') as f:

            while True:

                rec=pickle.load(f)

                print(rec)

    except EOFError:

        pass

    except Exception as e:

        print(e)


def search():

    c_id=int(input("Enter course id : "))

    try:

        with open('course.dat','rb') as f:

            while True:

                rec=pickle.load(f)

                if c_id==rec[0]:

                    print(rec)

                    break

    except EOFError:

        print(f"Course no {c_id} not found")

    except Exception as e:

        print(e)


def calculate():

    fees=[]

    try:

        with open('course.dat','rb') as f:

            while True:

                rec=pickle.load(f)

                fees.append(rec[3])

    except EOFError:

        avg=sum(fees)/len(fees)

        print(f"Average fees ={avg}")

    except Exception as e:

        print(e)



def update():

    l=[]

    try:

        with open('course.dat','rb') as f:

            while True:

                rec=pickle.load(f)

                rec[3]=rec[3]*1.1

                l.append(rec)                

    except EOFError:

        pass

    except Exception as e:

        print(e)

    with open('course.dat','wb') as f:

        for rec in l :

            pickle.dump(rec,f)

    print("Records have been updated ")

    display()

    

menu()


GRADE 12: PRACTICAL 8 : CSV FILES

 ''' Write a menu driven program to perform the following

functions on a csv file ‘ Student.csv’ 

i) Accept details of n students

and write into the file. The header will be :

[Student roll, Student Name, Student Marks]

ii)Display the contents of the file

iii)Function to display the average marks of all the

students who have got Distinction(above 75% marks) 

iv)Function to search for a given roll number and

display the details if found, else display an error.

'''

import csv


def menu():

    while True :

        ch=int(input("""MENU :

1.Accept

2.Display

3.Average

4.Search

5.Exit

"""))

        if ch==1:

            accept()

        elif ch==2:

            display()

        elif ch==3:

            average()

        elif ch==4:

            search()

        else:

            break


def accept():

    n=int(input("Enter no of records : "))

    with open("student.csv","a",newline="") as f:

        c=csv.writer(f)

        if f.tell()==0:

            c.writerow(['Student roll', 'Student Name',' Student Marks'])

        for i in range(n):

            roll=input("Enter roll no : ")

            name=input("Enter name : ")

            marks=input("Enter marks : ")

            c.writerow([roll,name,marks])


def display():

    with open("student.csv","r")as f:

        c = csv.reader(f)

        

        for a,b,c in c:

            print(a.ljust(15),b.ljust(15),c.ljust(15))

            

def average():

    with open("student.csv","r") as f:

        c=csv.reader(f)

        header=next(c)

        l=[]

        for i in c:

            mark=int(i[2])

            if mark>=75:

                l.append(mark)

        print(sum(l)/len(l))

                  

def search():

    roll=input("Enter roll number to be searched : ")

    with open("student.csv","r") as f:

        c=csv.reader(f)

        header=next(c)

        for i in c:

            if i[0]==roll:

                print("student found : ",i)

                break

        else:

            print("Student not found ")

    

menu()


GRADE 12 : PRACTICAL 7 : TEXT FILES

 '''

WAP that initializes the file Independence.txt to :

"And that's how India became

independent on 15th August 1947.

INDIA owes her freedom to

the sacrifice of the freedom fighters."

Further, write functions to :

a) Accept and add lines to the existing file.Now display

the file

b) Copy the words that start with a consonant , to a

file called words1.txt.Display the file.

c) Display the line number and the line that contains

the word 'India'(case insensitive)

d) Edit the file to change freedom to uppercase(FREEDOM)

and display the file.

'''


txt='''And that's how India became

independent on 15th August 1947.

INDIA owes her freedom to

the sacrifice of the freedom fighters.

'''

fobj=open('independence.txt', 'w')

fobj.write(txt)

fobj.close()


def main():

    while True:

        print('''Menu:

1) Accept and add lines to the existing file.

2) Copy the words that start with a consonant ,to a file called words1.txt.

3) Display the line number and the line that contains the word 'India'(case insensitive)

4) Edit the file to change freedom to uppercase(FREEDOM)

5) Exit''')

        try:

            ch=int(input("Enter your choice:"))

            if ch==1:

                accept()

            elif ch==2:

                consonant()

            elif ch==3:

                display()

            elif ch==4:

                edit()

            elif ch==5:

                print("Program terminated!")

                break

        except Exception as e:

            print("Error: ",e,'!')


def accept():

    with open ('independence.txt', 'a') as fobj:

        n=int(input("Enter desired number of lines:"))

        print(f'Enter {n} lines:')

        for i in range (n):

            line=input()

            fobj.write(line+'\n')

    with open('independence.txt','r') as fobj:

        print(fobj.read())

        

def consonant():

    with open('independence.txt', 'r') as fobj:

        fobj1=open('word1.txt','w')

        txt=fobj.read()

        words=txt.split()

        for i in words:

            if i[0].isalpha() and i[0] not in 'aeiouAEIOU':

                fobj1.write(i+'\n')

        fobj1.close()

    with open('word1.txt','r') as fobj:

        print(fobj.read())

    

def display():

    with open('independence.txt', 'r') as fobj:

        txt=fobj.read()

        txt=txt.lower()

        lines=txt.splitlines()

        for i in range(len(lines)):

            if 'india' in lines[i]:

                print (i+1,'.',lines[i])


def edit():

    with open('independence.txt', 'r') as fobj:

        txt=fobj.read()

        txt=txt.replace('freedom','FREEDOM')

    with open('independence.txt','w') as fobj:

        fobj.write(txt)

    with open('independence.txt', 'r') as fobj:

        print(fobj.read())

main()


               

       



GRADE 12 : PRACTICAL 6 : TEXT FILES

 ''' PRACTICAL 6

WAP to create functions that work on 'essay.txt' :

1. Accept data and store in the file

2. Display content of the file

3. Display Line Count, Word Count, Character Count

4. Search words that start with vowels

5. Change all the occurences of 'the' to THE

6. Exit

'''


def menu():

    while True:

        ch=int(input("""

MENU:

1. Accept Data

2. Display Data

3. Display Statistics

4. Search words that start with vowels

5. Change all occurences of 'the' to 'THE'.

6. Exit

Your choice : 

"""))

        if ch ==1:

            accept()

        elif ch ==2:

            display()

        elif ch ==3:

            count()

        elif ch ==4:

            search()

        elif ch ==5:

            change()

        else:

            break


def accept():

    n=int(input("Enter no. of lines"))

    with open('essay.txt','w') as fobj:

        print(f'Please enter {n} lines ')

        for i in range(n):

            line=input()

            fobj.write(line+'\n')

    

def display():

    try:

        fobj=open('essay.txt','r')

        content=fobj.read()

        print(content)

        fobj.close()

    except Exception as e:

        print("Error : ",e)

def count():

    try:

        fobj=open('essay.txt','r')

        text =fobj.read()

        cc=len(text)

        wc=len(text.split())

        lc=len(text.splitlines())

        print("Character count : ",cc)

        print("Word count : ",wc)

        print("Line count : ",lc)

        fobj.close()

    except Exception as e:

        print("Error : ",e)

        

def search():

    try:

        with open("essay.txt",'r') as fobj:

            text=fobj.read()

            words=text.split()

            for i in words:

                if i[0] in 'aeiouAEIOU':

                    print(i)

    except Exception as e:

        print("Error : ",e)

        

def change():

    with open('essay.txt','r') as fobj:

        text=fobj.read()

    text=text.replace('the','THE')

    with open('essay.txt','w') as fobj:

        fobj.write(text)

    


menu()



GRADE 12 : PRACTICAL 5 : EXCEPTION HANDLING

 '''You are developing a banking application where users can

withdraw money from their accounts. Implement a try-except block

to handle the scenario when a user tries to withdraw 

more money than their account balance, or if they try to withdra

a negative amount.

'''

#Answer:

account_balance = 100000.0  # Assume initial balance

def menu():

    global account_balance

    while True :

        ch=int(input("""MENU :

1.Withdraw Money

2.Check Balance

3.Exit"""))

        if ch==1:       

                   

            try:

                withdrawal_amount = float(input("Enter withdrawal amount: ")) 

                if withdrawal_amount > account_balance : 

                    raise ValueError("Insufficient balance")

                elif withdrawal_amount <0:

                    raise ValueError("Negative withdrawal amount")

                else: 

                    account_balance -= withdrawal_amount  

            except ValueError as e: 

                print(f"Error: {e}") 

            except Exception as e:

                print(f"Unexpected error occurred: {e}")

            else:

                print(f"Withdrawal successful")

            finally :

                print(f"Current balance: {account_balance}")

        elif ch==2:

            print(f"Account balance : ",account_balance)

        else:

            break

menu()   


GRADE 12 : PRACTICAL 4 : MODULES

 '''LAB 4 : WAP to accept a text from the user and perform encryption

and decryption on it using modules. The module should contain functions

that encrypt and decrypt the text, that take the text and key as parameters''' 



cipher.py


'''Module to encrypt and decrypt a code '''

#CONSTANT

KEY='ac!if@me#o$'

def encrypt(x,k=KEY):

    '''Function that accepts a message,a default arg k,

and returns the encrypted message'''

    return k.join(x)


def decrypt(x,k =KEY):

    '''Function that accepts an encrypted message , a default

argument k, and returns the decrypted message'''

    l=x.split(k)

    s=''.join(l)    

    return s



prog4.py 


import cipher

text = input("Enter the text that you want to encrypt : ")

key=input("Enter the key : ")

ec = cipher.encrypt(text,key)

print('original text : ',text)

print('encrypted text : ', ec)

dc = cipher.decrypt(ec,key)

print('decrypted text : ', dc)


GRADE 12: PRACTICAL 3 : MODULES

  '''LAB 3 : Write a menu driven Program to accept temperature

from the user and perform conversion to celcius or farenheit

as per the choice. Use modules that contain functions

to execute the required conversions'''

conversions.py

'''Module to convert between Farenheit and Celcius degrees'''

def faren_cel(f):
    '''accepts temperature in farenheit and returns the value in celcius'''
    return (f-32)*5/9                                                   

def cel_faren(c):
    '''accepts temperature in celcius and returns the value in farenheit'''
    return (c*9/5)+32


temperature.py

import conversions 
print(help(conversions))
while True:
    ch = int(input("""Menu:
1) Convert from farenheit to celcius
2) Convert from celcius to farenheit
3) Exit"""))
    if ch==1:
        temp=float(input("Enter the temperature in Farenheit"))
        cel=faren_cel(temp)
        print(f"It is {round(cel,2)} degrees in Celcius")
    elif ch==2:
        temp=float(input("Enter the temperature in Celcius"))
        far=cel_faren(temp)
        print(f"It is {round(far,2)} degrees in Farenheit")
    else:
        break

GRADE 12 : PRACTICAL 2 : FUNCTIONS

 '''

Write a menu driven program for the following functions:

1. accept(roll,name,score) :store student details in a

dictionary as :{roll : [name,score]}.

It will invoke function assign().

2. assign(roll): assign remarks as per the score,

and updates dictionary to : {roll : [name,score,remarks]}

------------------

|SCORE | REMARK  |

|>=50     | Selected      |

|<50       | Rejected      |

------------------

3. display(): view all the students who are selected.

4. search(roll): return the corresponding name and remark '''


d={}


def menu():

    while True:

        ch=int(input("""MENU:

1.Accept

2.Display

3.Search

4.Exit"""))

        if ch==1:

            roll=int(input("Enter Roll number : "))

            name=input("Enter name name : ")

            score=int(input("Enter Score : "))

            accept(roll,name,score)

        elif ch==2:

            display()

        elif ch==3:

            roll=int(input("Enter roll no to be searched"))

            print(search(roll))

        else:

            break


def accept(roll,name,score):

    d[roll] = [name,score]

    assign(roll)

    

def assign(roll):

    if d[roll][1]>=50:

        remark='Selected'

    else:

        remark='Rejected'

    d[roll].append(remark)

    

def display():

    for key in d:

        if d[key][2]=='Selected':

            print(d[key])


def search(roll):

    if roll in d.keys():

        return d[roll][0],d[roll][2]

    else:

        return 'Roll not found'


menu()


GRADE 12 : PRACTICAL 1 : FUNCTIONS

 '''

GRADE 12 : PRACTICAL 1

Write a menu driven program to create the following functions:

a> accept() to accept the name of 10 areas & their PIN Codes in 2 lists.

b> search() to search for an area. If found, display the city and PIN Code, otherwise display 'Search Unsuccessful'

c> update() for updating the PIN Code of a certain area if found,otherwise display 'Update Unsuccessful'  

d> A function display() to populate the above 2 lists into a dictionary and display the same'''


area_list=[]

pin_list=[]


def menu():

    while True :

        ch=int(input("""MENU :

1>ACCEPT

2>SEARCH

3>UPDATE

4>DISPLAY

5>EXIT

Enter choice : """))

        if ch==1:

            accept()

        elif ch==2:

            search()

        elif ch==3:

            update()

        elif ch==4:

            display()

        else:

            break


def accept():

    for i in range(10):

        area=input("Enter area : ")

        pin=int(input("Enter pincode : "))

        area_list.append(area)

        pin_list.append(pin)

        

def search():

    a=input("Enter area to search : ")

    if a in area_list:

        i = area_list.index(a)

        print("Pincode is : ",pin_list[i])

    else :

        print("Search unsuccessful ")

        

def update():

    a=input("Enter area to updated : ")

    if a in area_list:

        i = area_list.index(a)

        print("Pincode is : ",pin_list[i])

        pin=int(input("Enter new pincode : "))

        pin_list[i]=pin     

    else :

        print("Update unsuccessful ")


def display():

    d=dict(zip(area_list,pin_list))

    print(d)


menu()






Binary : Example 2

  import pickle


def accept():

    with open('xyz.dat','wb') as f:

        pickle.dump('Hi there',f)

        pickle.dump(12345678,f)

        pickle.dump(('ek','do','teen'),f)

        pickle.dump(['un','dos','tres'],f)

        pickle.dump({1:'one',2:'two',3:'three'},f)


def display():

    with open('xyz.dat','rb') as f:

        for i in range(5):

            rec=pickle.load(f)

            print(rec)

        #rec=pickle.load(f)

accept()

display()

        


Binary : Example1

  '''WAP to accept n medical records and display the same'''

import pickle


def accept():

    n=int(input("Enter no of records " ))

    with open('medical.dat','ab') as f:

        for i in range(n):

            name=input("Enter name : ")

            age=int(input("Enter age : "))

            sugar=int(input("Enter sugar lev(mg/dL) : "))

            bp=input("Enter bp(mmHg) : ")

            d={'name':name,'age':age,'sugar':sugar,'bp':bp}

            pickle.dump(d,f)

        

def display():

    try:

        with open('medicals.dat','rb') as f:

            while True:

                rec=pickle.load(f)

                print(rec)

    except EOFError:

        pass

    except Exception as e:

        print(e)

accept()

display()

        


CSV: An Example

  import csv


def accept():

    with open('players.csv','a',newline='') as f :

        c=csv.writer(f)

        n=int(input('enter no of lines : '))

        if f.tell()==0:

            c.writerow(['Name','games','goals'])

        for i in range(n):

            name=input("Enter name : ")

            games=int(input("Enter no of games played : "))

            goals= int(input("enter no of goals : "))

            l=[name,games,goals]

            c.writerow(l)

            

def disp():

    with open('players.csv','r') as f:

        c=csv.reader(f)

        tot=0

        header=next(c)

        print(header)

        for i in c :

            print(i)

            tot+=int(i[2])

        print('Total = ',tot)

accept()

disp()


Sample project report

PROJECT REPORT TEMPLATE