0% found this document useful (0 votes)
9 views

CS Practical file hiya FINALLL (1)

The document is a programming file for a Computer Science course at Fr. Agnel School, New Delhi, for the session 2023-24. It contains a series of programming tasks and solutions, primarily focused on Python, including functions for checking palindromes, counting character frequencies, and manipulating lists and dictionaries. The document serves as a comprehensive guide for students to practice and implement various programming concepts.

Uploaded by

Manya Juneja
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

CS Practical file hiya FINALLL (1)

The document is a programming file for a Computer Science course at Fr. Agnel School, New Delhi, for the session 2023-24. It contains a series of programming tasks and solutions, primarily focused on Python, including functions for checking palindromes, counting character frequencies, and manipulating lists and dictionaries. The document serves as a comprehensive guide for students to practice and implement various programming concepts.

Uploaded by

Manya Juneja
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 61

FR.

AGNEL SCHOOL, NEW DELHI


Session 2023-24

COMPUTER
SCIENCE
PROGRAMMING
FILE

SUBMITTED BY:
NAME : HIYA
PATWAL
1|Page
FR. AGNEL SCHOOL, NEW DELHI
Session 2023-24

CLASS :
XII C
BOARD ROLL NO :

2|Page
FR. AGNEL SCHOOL, NEW DELHI
Session 2023-24

INDEX
S.N PROGRAM Page
O. No.
1 Write a program using user defined function to check 6
whether the entered string is a palindrome or not.
2 Write a program using user defined function to show 7
statistics of characters in the given line (count the number
of alphabets, uppercase alphabets, lowercase alphabets,
digits, spaces, and other special characters).
3 Write a program using user defined function to count the 9
frequency of each character in a string.
4 Write a program using user defined function to remove all 11
duplicates numbers from the given list of numbers.
5 Write a program using user defined function to print the 13
largest and the second largest element from a list of
numbers.
6 Write a program using user defined function to find an 15
element in a list. If the element is present, the function
returns position of the element. Print an appropriate
message if the number is not present in the list.
7 Write a program using user defined function to find the 17
GCD of two numbers.
8 Write a program using user defined function to find LCM 18
of two numbers.
9 Write a program using user defined function to print prime 19
numbers between 1 and 100.
10 Write a menu driven program to input your friends’ names 20
and their Phone Numbers and store them in the dictionary
as the key-value pair. Perform the following operations on
the dictionary:
a) Display the name and phone number of all your
friends.
b) Add a new key-value pair in this dictionary and
display the modified dictionary.
c) Delete a friend from the dictionary.
3|Page
FR. AGNEL SCHOOL, NEW DELHI
Session 2023-24

d) Modify the phone number of an existing friend.


e) Check if a friend is present in the dictionary or
not.
f) Display the dictionary in sorted order of names.
11 Write a program that checks if the two same values in a 26
dictionary have different keys. That is, for dictionary
D1={‘a’:10, ‘b’:20. ‘c’:10}, the program should print “2
keys have same values” and for dictionary D2={‘a’:10,
‘b’:20, ‘c’:30}, the program should print “No keys have
same values”.
12 Write a menu driven program for the following tasks: 28
a) To input two numbers from user and generate any
integer random number between them (including
both limits).
b) To input two numbers from user and generate a
random integer between them with a step of 3.
c) To input two numbers from user and generate any
random floating number between them using random
().
13 Write a function in Python to read the content of a text file 31
“DELHI.TXT” and display all those lines on screen,
which are either starting with ‘D’ or starting with ‘M.’
14 Write a function in Python to count the number of “Me” 32
or “My” words present in a text file “DIARY.TXT”.
15 Assume that a text file named “TEXT1.TXT” already 33
contains some text into it. Write a function named
vowelwords( ) that reads the file TEXT1.TXT to count
number of words in the file and create a new file named
“TEXT2.TXT” which contain only those words from the
file TEXT1.TXT which don’t start with upper case vowel
(i.e A, E, I, O ,U).
16 Write a menu driven program to add, delete, modify and 35
display records in a binary file ‘STUDENT.DAT’ in
which each record is stored in the form of list with Roll
number, Name and Marks.
4|Page
FR. AGNEL SCHOOL, NEW DELHI
Session 2023-24

17 Write the program that defines a function to store new 41


records of VEHICLE in the binary data file
“VEHICLE.DAT” till the user desires.
VEHICLE = {‘Vehicle Code’: 11,
‘Vehicle Name’: ‘Wagon R’, ‘Cost’: 604000}
18 Write the program that defines a function to read data of 43
VEHICLE from the data file “VEHICLE.DAT” and
prints, counts and stores the details of all Vehicles whose
name is ‘WAGON R’ and cost is greater than 600000 in
another file “NEWVEHICLE.DAT”.
(Refer to file created in Q 17)
19 Create a CSV file (emp.csv) with fields- empno, name 45
and salary. Write a menu driven program to perform
following operations on emp.csv.
a) To read the content of file emp.csv and display only
those records where salary is 4000 or above.
b) To read the content of file emp.csv and display the
employee record whose name begins from ‘S’ also
show no. of employee with first letter ‘S’ out of
total record.
c) To increase the salary by 2000 for a given employee
code.
20 Write a Python program to : 50
● Define a function PushPlayers(P, N) to Push the Player
name N into a List implemented stack named P.
● Define a function PopPlayers(P) to Pop and display the
last Player name from the stack P. The function should
display the message “Empty Stack” if stack P does not
have any value in it.
● Define a function ShowPlayers(P) to display the content
of the stack P.
21 Write a program that fetches and displays all the records 54
from a table ‘Student’ present in the database ‘SCHOOL’
in mySQL.
22 Write a program that takes input various field values from 55
user and insert record in the table ‘Student’ present in the

5|Page
FR. AGNEL SCHOOL, NEW DELHI
Session 2023-24

database ‘SCHOOL’ in mySQL till user’s choice is ‘Y’.


23 Write a program that asks the user to enter a roll number 57
and delete the record of that roll number from a table
‘Student’ present in the database ‘SCHOOL’ in mySQL.
24 Write a program that asks the user to enter a roll number 59
and increase the marks of that roll number from a table
‘Student’ present in the database ‘SCHOOL’ in mySQL.
25 Write a program that asks the user to enter the marks 60
above which the records are to be displayed from a table
‘Student’ present in the database ‘SCHOOL’ in mySQL.
26 SQL QUERIES 62

PROGRAM #1

6|Page
FR. AGNEL SCHOOL, NEW DELHI
Session 2023-24

# Write a program using user defined function to check whether the


entered string is a palindrome or not.
def is_palindrome(string : str):

ispalin = string == string[::-1]

if ispalin:

print ("String is a palindrome")

else:

print ("String is not a palindrome")

string = input("Enter a string ")

is_palindrome(string)

OUTPUT:

PROGRAM#2

7|Page
FR. AGNEL SCHOOL, NEW DELHI
Session 2023-24

#Write a program using user defined function to show statistics of


characters in the given line (count the number of alphabets, uppercase
alphabets, lowercase alphabets, digits, spaces, and other special characters).

def char_stat(line):

a,ua,la,d,s,osc=0,0,0,0,0,0

for i in line:

if i.isalpha() == True:

a += 1

if i.isupper() == True:

ua += 1

elif i.islower() == True:

la += 1

elif i.isdigit() == True:

d += 1

elif i.isspace() == True:

s += 1

else:

osc += 1

print("Statistics of the given line:-")

print("Alphabets :",a)

print("Uppercase alphabets :",ua)

print("Lowercase alphabets :",la)

print("Digits :",d)

8|Page
FR. AGNEL SCHOOL, NEW DELHI
Session 2023-24

print("Spaces :",s)

print("Other special characters :",osc)

line = input("Enter line : ")

char_stat(line)

OUTPUT:

PROGRAM#3
9|Page
FR. AGNEL SCHOOL, NEW DELHI
Session 2023-24

#Write a program using user defined function to count the frequency of


each character in a string.
def chars_frequency(istr):
chars = []

count = 0

for i in istr:

if i not in chars:

chars += [i]

else:

continue

count = 0

for j in istr:

if i == j:

count +=1

print("The frequency of {} = {}".format(i,count))

istr = input("Enter String : ")

chars_frequency(istr)

OUTPUT:

10 | P a g e
FR. AGNEL SCHOOL, NEW DELHI
Session 2023-24

Program#4

11 | P a g e
FR. AGNEL SCHOOL, NEW DELHI
Session 2023-24

#Write a program using user defined function to remove all duplicates


numbers from the given list of numbers.
def remove_duplicate(l):

temp=[]

for i in l:

if i not in temp:

temp.append(i)

return temp

l=[]

n=int(input("Enter the number of elements to be entered in the list"))

for i in range(n):

num=int(input("Enter a number:"))

l.append(num)

print("The original list is")

print(l)

l=remove_duplicate(l)

print("List after removing duplicates :")

print(l)

OUTPUT:

12 | P a g e
FR. AGNEL SCHOOL, NEW DELHI
Session 2023-24

Program#5

13 | P a g e
FR. AGNEL SCHOOL, NEW DELHI
Session 2023-24

#Write a program using user defined function to print the largest and the
second largest element from a list of numbers.
def large(l):

lar1 = l[0]

lar2 = l[0]

for i in l:

if lar1 < i:

lar1= i

for i in l:

if i<lar1 and i>lar2:

lar2=i

print("Largest number in list:",lar1)

print("Second largest number in list:",lar2)

l=[]

n=int(input("Enter the number of elements to be entered in the list"))

for i in range(n):

num=int(input("Enter a number:"))

l.append(num)

print("The given list is")

print(l)

large(l)

OUTPUT:
14 | P a g e
FR. AGNEL SCHOOL, NEW DELHI
Session 2023-24

Program#6

15 | P a g e
FR. AGNEL SCHOOL, NEW DELHI
Session 2023-24

#Write a program using user defined function to find an element in a list.


If the element is present, the function returns position of the element. Print an
appropriate message if the number is not present in the list.
def search(l,e):

flag = False

for i in range(len(l)):

if l[i] == e:

flag = True

print("Element found at index no.",i)

break

if flag == False:

print("Element not found in list")

l=[]

n=int(input("Enter the number of elements to be entered in the list"))

for i in range(n):

num=int(input("Enter a number:"))

l.append(num)

elmt = int(input("Enter element to be searched: "))

search(l,elmt)

OUTPUT:

16 | P a g e
FR. AGNEL SCHOOL, NEW DELHI
Session 2023-24

17 | P a g e
FR. AGNEL SCHOOL, NEW DELHI
Session 2023-24

Program#7
#Write a program using user defined function to find the GCD of two
numbers
def gcd(x,y):

while y!=0:

r=x%y

x,y=y,r

return x

a=int(input("Enter first number:"))

b=int(input("Enter second number:"))

if a>b:

g=gcd(a,b)

else:

g=gcd(b,a)

print("GCD of ",a, "and",b, "is ", g)

OUTPUT:

18 | P a g e
FR. AGNEL SCHOOL, NEW DELHI
Session 2023-24

Program#8
#Write a program using user defined function to find LCM of two
numbers.
def LCM(a,b):

if a>b:

m=a

else:

m=b

while True:

if m%a==0 and m%b==0:

print("LCM of", a, "and", b , "=",m)

break

else:

m=m+1

a=int(input("Enter first number:"))

b=int(input("Enter second number:"))

LCM(a,b)

OUTPUT:

Program#9
19 | P a g e
FR. AGNEL SCHOOL, NEW DELHI
Session 2023-24

#Write a program using user defined function to print prime numbers


between 1 and 100.
def print_prime():

print("Prime numbers between 1 and 100 are")

for n in range(2,101):

count=0

c=1

while c<=n:

if n%c==0:

count+=1

c+=1

if count==2:

print(n,end=",")

print_prime()

OUTPUT:

Program#10

20 | P a g e
FR. AGNEL SCHOOL, NEW DELHI
Session 2023-24

#Write a menu driven program to input your friends’ names and their
Phone Numbers and store them in the dictionary as the key-value pair.
Perform the following operations on the dictionary:
a) Display the name and phone number of all your friends
b) Add a new key-value pair in this dictionary and display the
modified dictionary
c) Delete a friend from the dictionary
d) Modify the phone number of an existing friend
e) Check if a friend is present in the dictionary or not
f) Display the dictionary in sorted order of names
import sys

def addrec():

fname = input("Enter Friend's name: ")

num = int(input("Enter Ph. Number: "))

records[fname] = num

print("Record written\n")

displayrec()

def displayrec():

print("Friend name\tPh. Number")

for i in records:

print(i,records[i],sep="\t\t")

print()

def srchrec():

fname = input("Enter Friend's name: ")

flg = False

for i in records:

21 | P a g e
FR. AGNEL SCHOOL, NEW DELHI
Session 2023-24

if i == fname:

flg = True

print("Friend is present\n")

break

if flg == False:

print("Friend is not present\n")

def modrec():

fname = input("Enter Friend's name: ")

flg = False

for i in records:

if i == fname:

nnum = int(input("Enter New number: "))

records[i] = nnum

flg = True

print("Record modified\n")

break

if flg == False:

print("Record is not present\n")

def delrec():

fname = input("Enter Friend's name: ")

flg = False

for i in records:

if i == fname:

22 | P a g e
FR. AGNEL SCHOOL, NEW DELHI
Session 2023-24

flg = True

records.pop(i)

print("Record deleted\n")

break

if flg == False:

print("Record is not present\n")

def srtdrec():

l=[]

for i in records:

l += [i]

for i in range(len(l)-1):

for j in range(len(l)-1-i):

if l[j] > l[j+1]:

l[j],l[j+1] = l[j+1],l[j]

print("Friend name\tPh. Number")

for i in l:

print(i,records[i],sep="\t\t")

print()

records = {}

while True:

print("Main Menu")

print("Type 1 to Display all records")

23 | P a g e
FR. AGNEL SCHOOL, NEW DELHI
Session 2023-24

print("Type 2 to Add new record")

print("Type 3 to Delete a record")

print("Type 4 to Modify a record")

print("Type 5 to Check if a record is present")

print("Type 6 to Display sorted records")

print("Type 7 to Quit")

print()

choice=int(input("Enter Your choice: "))

print()

if choice == 1:

displayrec()

elif choice == 2:

addrec()

elif choice == 3:

delrec()

elif choice == 4:

modrec()

elif choice == 5:

srchrec()

elif choice == 6:

srtdrec()

elif choice == 7:

sys.exit()

24 | P a g e
FR. AGNEL SCHOOL, NEW DELHI
Session 2023-24

else:

print("Invalid Choice\n")

OUTPUT:

25 | P a g e
FR. AGNEL SCHOOL, NEW DELHI
Session 2023-24

Program#11
#Write a program that checks if the two same values in a dictionary have
different keys. That is , for dictionary D1={‘a’:10, ‘b’:20. ‘c’:10}, the program
should print “2 keys have same values” and for dictionary D2={‘a’:10, ‘b’:20,
‘c’:30}, the program should print “No keys have same values”.
def dictCheck(d1):

d2={}

c=0

for i in d1:

if d1[i] not in d2:

d2[d1[i]]=1

else:

d2[d1[i]]+=1

for i in d2:

26 | P a g e
FR. AGNEL SCHOOL, NEW DELHI
Session 2023-24

if d2[i]>=2:

print(d2[i]," keys have same value:",i)

c+=1

if c==0:

print("No keys have same values")

D1 = {'a':10,'b':20,'c':10}

print("For dictionary :",D1)

dictCheck(D1)

D2 = {'a':10,'b':20,'c':30}

print("\nFor dictionary :",D2)

dictCheck(D2)

D3 = {'a':10,'b':20,'c':10,'d':10,'e':20,'f':30}

print("\nFor dictionary :",D3)

dictCheck(D3)

OUTPUT:

27 | P a g e
FR. AGNEL SCHOOL, NEW DELHI
Session 2023-24

Program#12
#Write a menu driven program for the following tasks-
I. To input two numbers from user and generate any integer random
number between them (including both limits)
II. To input two numbers from user and generate a random integer
between them with a step of 3
III. To input two numbers from user and generate any random floating
number between them using random ()
import sys

import random

def random_1():

a = int(input("Enter first number: "))

b = int(input("Enter second number: "))

if a > b:

a,b = b,a

n = random.randint(a,b)
28 | P a g e
FR. AGNEL SCHOOL, NEW DELHI
Session 2023-24

print("random no. N for a<=N<=b :",n)

print()

def random_2():

a = int(input("Enter first number: "))

b = int(input("Enter second number: "))

if a > b:

a,b = b,a

n = random.randrange(a,b,3)

print("random no. N for a<=N<b with step 3 :",n)

print()

def random_3():

a = int(input("Enter first number: "))

b = int(input("Enter second number: "))

if a > b:

a,b = b,a

n = random.random()*(b-a) + a

print("random float no. N for a<=N<=b :",n)

print()

while True:

print("Main Menu")

print("Type 1 for random no. N for a<=N<=b")

print("Type 2 to random no. N for a<=N<b with step 3")

print("Type 3 to random float no. N such that a<=N<=b")

29 | P a g e
FR. AGNEL SCHOOL, NEW DELHI
Session 2023-24

print("Type 4 to Quit")

print()

choice=int(input("Enter Your choice: "))

print()

if choice == 1:

random_1()

elif choice == 2:

random_2()

elif choice == 3:

random_3()

elif choice == 4:

sys.exit()

else:

print("Invalid Choice\n")

OUTPUT:

30 | P a g e
FR. AGNEL SCHOOL, NEW DELHI
Session 2023-24

Program#13
#Write a function in Python to read the content of a text file “DELHI.TXT”
and display all those lines on screen, which are either starting with ‘D’ or
starting with ‘M’
def readfromfile():

f = open("DELHI.txt","r")

lines = f.readlines()

for l in lines:

if l[0] in "DM":

31 | P a g e
FR. AGNEL SCHOOL, NEW DELHI
Session 2023-24

print(l)

f.close()

readfromfile()

OUTPUT:

Program#14
#Write a function in Python to count the number of “Me” or “My” words
present in a text file “DIARY.TXT”.
def read_memy():

f = open("DIARY.txt","r")

text = f.read()

words = text.split()

count_me = 0

count_my = 0

32 | P a g e
FR. AGNEL SCHOOL, NEW DELHI
Session 2023-24

for wrd in words:

if wrd.strip("., ").upper()=="ME":

count_me += 1

if wrd.strip("., ").upper()=="MY":

count_my += 1

print("Count of Me in file DIARY.txt :",count_me)

print("Count of My in file DIARY.txt :",count_my)

f.close()

read_memy()

OUTPUT:

Program#15
#Assume that a text file named “TEXT1.TXT” already contains some text
into it. Write a function named vowelwords( ) that reads the file TEXT1.TXT
to count number of words in the file and create a new file named
“TEXT2.TXT” which contain only those words from the file TEXT1.TXT
which don’t start with upper case vowel (i.e A, E, I, O ,U).
def vowelwords():

f = open("TEXT1.txt","r")

g = open("TEXT2.txt","w")

text = f.read()

33 | P a g e
FR. AGNEL SCHOOL, NEW DELHI
Session 2023-24

words = text.split()

totalwrds = len(words)

print("Number of words in file TEXT1.txt =",totalwrds)

print()

for wrd in words:

if wrd[0] not in "AEIOUaeiou":

g.write(wrd.strip(".,")+"\n")

print("Words from TEXT1.txt not starting with A,E,I,O,U written in TEXT2.txt\n")

f.close()

g.close()

vowelwords()

NOTEPAD AND OUTPUT:

34 | P a g e
FR. AGNEL SCHOOL, NEW DELHI
Session 2023-24

Program#16
#Write a menu driven program to add, delete, modify and display records
in a binary file ‘STUDENT.DAT’ in which each record is stored in the form of
list with Roll number, Name and Marks.
import sys

35 | P a g e
FR. AGNEL SCHOOL, NEW DELHI
Session 2023-24

import pickle

def addrec():

rollno = int(input("Enter Roll No.: "))

name = input("Enter Name: ")

marks = float(input("Enter Marks: "))

record = [rollno,name,marks]

f = open("STUDENT.dat","ab")

pickle.dump(record,f)

f.close()

print("Record Written in file STUDENT.dat\n")

def dsplyrec():

f = open("STUDENT.dat","rb")

print("RollNo.\tName\tMarks")

while True:

try:

rec = pickle.load(f)

print(rec[0],rec[1],rec[2],sep="\t")

except EOFError:

break

f.close()

print()

def modrec():

r = int(input("Enter Rollno. of record to be modified: "))

36 | P a g e
FR. AGNEL SCHOOL, NEW DELHI
Session 2023-24

f = open("STUDENT.dat","rb")

records = []

while True:

try:

rec = pickle.load(f)

records += [rec]

except EOFError:

break

f.close()

name = input("Enter new name: ")

mrks = float(input("Enter new marks: "))

for rec in records:

if rec[0] == r:

rec[1] = name

rec[2] = mrks

f = open("STUDENT.dat","wb")

for rec in records:

pickle.dump(rec,f)

f.close()

print("Record updated\n")

def delrec():

r = int(input("Enter Rollno. of record to be deleted: "))

f = open("STUDENT.dat","rb")

37 | P a g e
FR. AGNEL SCHOOL, NEW DELHI
Session 2023-24

records=[]

while True:

try:

rec=pickle.load(f)

if rec[0] != r:

records += [rec]

except EOFError:

break

f.close()

f = open("STUDENT.dat","wb")

for rec in records:

pickle.dump(rec,f)

f.close()

print("Record deleted\n")

while True:

print("Main Menu")

print("Type 1 to add a new record")

print("Type 2 to display all records")

print("Type 3 to modify record")

print("Type 4 to delete a record")

print("Type 5 to quit program")

print()

choice=int(input("Enter Your choice: "))

38 | P a g e
FR. AGNEL SCHOOL, NEW DELHI
Session 2023-24

print()

if choice == 1:

addrec()

elif choice == 2:

dsplyrec()

elif choice == 3:

modrec()

elif choice == 4:

delrec()

elif choice == 5:

sys.exit()

else:

print("Invalid Choice\n")

OUTPUT:

39 | P a g e
FR. AGNEL SCHOOL, NEW DELHI
Session 2023-24

40 | P a g e
FR. AGNEL SCHOOL, NEW DELHI
Session 2023-24

Program#17

41 | P a g e
FR. AGNEL SCHOOL, NEW DELHI
Session 2023-24

#Write the program that defines a function to store new records of


VEHICLE in the binary data file “VEHICLE.DAT” till the user desires.
VEHICLE ={ ‘Vehicle Code’ : 11 , ‘Vehicle Name’ : ‘Wagon R’ , ‘Cost’ :
604000 }

import pickle

def vclfunc():

f = open("VEHICLE.dat","wb")

flg = True

while True:

if flg == True:

vclcode = int(input("Enter Vehicle Code : "))

vclname = input("Enter Vehicle Name : ")

vclcost = int(input("Enter Cost : "))

print()

rec = {"Vehicle Code":vclcode,"Vehicle Name":vclname,"Cost":vclcost}

pickle.dump(rec,f)

print("Record written in VEHICLE.dat\n")

ch = input("Do you wish to continue (Y/N): ")

print()

if ch in "Yy":

flg = True

continue

elif ch in "Nn":
42 | P a g e
FR. AGNEL SCHOOL, NEW DELHI
Session 2023-24

break

else:

print("Invalid choice\n")

flg = False

f.close()

vclfunc()

OUTPUT:

Program#18

43 | P a g e
FR. AGNEL SCHOOL, NEW DELHI
Session 2023-24

#Write the program that defines a function to read data of VEHICLE from
the data file “VEHICLE.DAT” and prints, counts and stores the details of all
Vehicles whose name is
‘WAGON R’ and cost is greater than 600000 in another file
“NEWVEHICLE.DAT”. (Refer to file created in Q 17)
import pickle

def nVcl():

f = open("VEHICLE.dat","rb")

vhcls = []

while True:

try:

rec = pickle.load(f)

vhcls += [rec]

except EOFError:

break

f.close()

count = 0

g = open("NEWVEHICLE.dat","wb")

print("Vehicle Code\tVehicle Name\tCost")

for i in vhcls:

if i["Vehicle Name"].upper() == "WAGON R" and i["Cost"] > 600000:

print(i["Vehicle Code"],i["Vehicle Name"],i["Cost"],sep = "\t\t")

count += 1

pickle.dump(i,g)

44 | P a g e
FR. AGNEL SCHOOL, NEW DELHI
Session 2023-24

print()

g.close()

print(count,"records written in NEWVEHICLE.dat")

nVcl()

OUTPUT:

Program#19

Create a CSV file (emp.csv) with fields- empno, name and salary. Write a
45 | P a g e
FR. AGNEL SCHOOL, NEW DELHI
Session 2023-24

menu driven program to perform following operations on emp.csv


I. To read the content of file emp.csv and display only those records where
salary is 4000 or above
II. To read the content of file emp.csv and display the employee
record whose name begins from ‘S’ also show no. of employee with
first letter ‘S’ out of total record.
III. To increase the salary by 2000 for a given employee code.

import sys

import csv

def dis_1Rec():

f = open("emp.csv","r")

readobj = csv.reader(f)

print("Empno.\tName\tSalary")

for i in readobj:

if i[2].isalpha() == True:

continue

elif int(i[2]) >= 4000:

print(i[0],i[1],i[2],sep="\t")

print()

def dis_2Rec():

f = open("emp.csv","r")

readobj = csv.reader(f)

count = 0

print("Empno.\tName\tSalary")

for i in readobj:

46 | P a g e
FR. AGNEL SCHOOL, NEW DELHI
Session 2023-24

if i[1][0] in "Ss":

count += 1

print(i[0],i[1],i[2],sep="\t")

print()

print("No. of employee with first letter S =",count)

f.close()

print()

def incrRec():

f = open("emp.csv","r")

readobj = csv.reader(f)

records = []

for i in readobj:

records += [i]

f.close()

empno = input("Enter Employee code: ")

for i in records:

if i[0] == empno:

i[2] = int(i[2])

i[2] += 2000

f = open("emp.csv","w",newline = "")

wobj = csv.writer(f)

wobj.writerows(records)

f.close()

47 | P a g e
FR. AGNEL SCHOOL, NEW DELHI
Session 2023-24

print("Salary of empno {} increased by 2000".format(empno))

print()

def addRec():

f=open("emp.csv",'a',newline='')

wobj=csv.writer(f)

ec=input("Enter Employee code: ")

en=input("Enter Employee name: ")

es=int(input("Enter Employee salary: "))

l=[ec,en,es]

wobj.writerow(l)

f.close()

print("Record added!")

while True:

print("Main Menu")

print("Type 1 to Add a record")

print("Type 2 to Display records with salary >= 4000")

print("Type 3 to Display and count records with name staring with S")

print("Type 4 to Increase salary by 2000 for a record")

print("Type 5 to Quit program")

print()

choice=input("Enter Your choice: ")

print()

if choice == "1":

48 | P a g e
FR. AGNEL SCHOOL, NEW DELHI
Session 2023-24

addRec()

elif choice == "2":

dis_1Rec()

elif choice == "3":

dis_2Rec()

elif choice == "4":

incrRec()

elif choice == "5":

sys.exit()

else:

print("Invalid Choice\n")

OUTPUT:

49 | P a g e
FR. AGNEL SCHOOL, NEW DELHI
Session 2023-24

Program#20
50 | P a g e
FR. AGNEL SCHOOL, NEW DELHI
Session 2023-24

#Write a Python program to :


● Define a function PushPlayers(P, N) to Push the Player name N into a
List implemented stack named P.
● Define a function PopPlayers(P) to Pop and display the last Player name
from the stack P. The function should display the message “Empty Stack” if
stack P does not have any value in it.
● Define a function ShowPlayers(P) to display the content of the stack P.

import sys

def PushPlayers(P,N):

P.append(N)

print("Stack Updated!")

def PopPlayers(P):

if P:

print("Player popped =", P.pop())

else:

print("Underflow in stack!")

def ShowPlayers(P):

if P==[]:

print("Underflow in stack!")

else:

print("Player list in Stack-")

for i in range(len(P)-1,-1,-1):

print(P[i])

51 | P a g e
FR. AGNEL SCHOOL, NEW DELHI
Session 2023-24

def main():

P = [] #Stack declaration

while True:

print("\nMAIN-MENU")

print("1. PUSH ")

print("2. POP")

print("3. DISPLAY")

print("4. QUIT")

print()

ch = input("Enter choice: ")

print()

if ch == "1":

N=input("Enter the name of player :")

PushPlayers(P,N)

elif ch == "2":

PopPlayers(P)

elif ch == "3":

ShowPlayers(P)

elif ch == "4":

sys.exit()

else:

print("Invalid choice\n")

main()

52 | P a g e
FR. AGNEL SCHOOL, NEW DELHI
Session 2023-24

OUTPUT:

53 | P a g e
FR. AGNEL SCHOOL, NEW DELHI
Session 2023-24

Program#21
#Write a program that fetches and displays all the records from a table
‘Student’ present in the database ‘SCHOOL’ in mySQL.
import mysql.connector

con = mysql.connector.connect(host = "localhost",

user = "root",

passwd = "1604@2005",

54 | P a g e
FR. AGNEL SCHOOL, NEW DELHI
Session 2023-24

database = "SCHOOL")

cur = con.cursor()

cur.execute("Select * from Student")

records = cur.fetchall()

print("| ROLLNO | STUDENT NAME | MARKS |")

for i in records:

print('|',i[0],' '*(5-len(str(i[0]))),'|',

i[1],' '*(11-len(i[1])),'|',

i[2],' '*(4-len(str(i[2]))),'|')

cur.close()

con.close()

output:

Program#22
#Write a program that takes input various field values from user and insert
record in the table ‘Student’ present in the database ‘SCHOOL’ in mySQL
till user’s choice is ‘Y’
import mysql.connector

con = mysql.connector.connect(host = "localhost",

user = "root",

passwd = "1604@2005",

55 | P a g e
FR. AGNEL SCHOOL, NEW DELHI
Session 2023-24

database = "SCHOOL")

cur = con.cursor()

flg = True

while True:

if flg == True:

rl = int(input("Enter Rollno.: "))

nm = input("Enter Name: ")

mr = float(input("Enter Marks: "))

print()

cur.execute("Insert into Student values({},'{}',{})".format(rl,nm,mr))

con.commit()

ch = input("Do you wish to continue(Y/N) : ")

print()

if ch in "Yy":

flg = True

continue

elif ch in "Nn":

break

else:

flg = False

print("Invalid choice\n")

cur.close()

56 | P a g e
FR. AGNEL SCHOOL, NEW DELHI
Session 2023-24

con.close()

output:

Program#23
#Write a program that asks the user to enter a roll number and delete the
record of that roll number from a table ‘Student’ present in the database
‘SCHOOL’ in mySQL
import mysql.connector

con = mysql.connector.connect(host = "localhost",

user = "root",

passwd = "1604@2005",

database = "SCHOOL")
57 | P a g e
FR. AGNEL SCHOOL, NEW DELHI
Session 2023-24

cur = con.cursor()

rl = int(input("Enter Rollno.: "))

cur.execute("Delete from Student where Rollno = {}".format(rl))

con.commit()

print("Record Deleted")

cur.close()

con.close()

output:

Again running program#21 to display changes:

58 | P a g e
FR. AGNEL SCHOOL, NEW DELHI
Session 2023-24

Program#24
#Write a program that asks the user to enter a roll number and increase the
marks of that roll number from a table ‘Student’ present in the database
‘SCHOOL’ in mySQL
import mysql.connector

con = mysql.connector.connect(host = "localhost",user = "root",


passwd="1604@2005",database = "SCHOOL")

cur = con.cursor()

rl = int(input("Enter Rollno.: "))

imr = float(input("Enter amount of marks to be increased: "))

cur.execute("Update Student set Marks = Marks + {} where Rollno = {}".format(imr,rl))

con.commit()

59 | P a g e
FR. AGNEL SCHOOL, NEW DELHI
Session 2023-24

print("Record Updated")

cur.close()

con.close()

output:

Again running program#21 to display changes:

Program#25
#Write a program that asks the user to enter the marks above which the
records are to be displayed from a table ‘Student’ present in the database
‘SCHOOL’ in mySQL.
import mysql.connector

con = mysql.connector.connect(host = "localhost",

user = "root",

passwd = "1604@2005",

database = "SCHOOL")

cur = con.cursor()

mr = float(input("Enter Marks: "))

print()

60 | P a g e
FR. AGNEL SCHOOL, NEW DELHI
Session 2023-24

cur.execute("Select * from Student where Marks > {}".format(mr))

records = cur.fetchall()

print("| ROLLNO | STUDENT NAME | MARKS |")

for i in records:

print('|',i[0],' '*(5-len(str(i[0]))),'|',

i[1],' '*(11-len(i[1])),'|',

i[2],' '*(4-len(str(i[2]))),'|')

cur.close()

con.close()

output:

61 | P a g e

You might also like