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

CS PROGRAM FILE

PROGRAMS
TASK 1-WAPP a function-based program to determine if a given year is a leap year or not.

SOURCE CODE:

def leap_year():

year=int(input("enter year:"))

if year % 4 ==0:

print(year, " is a leap year")

else:

print(year,'is not a leap year')

leap_year()

OUTPUT:

TASK-2: Define a function Pattern(N) to display the following pattern when N=4:

212

32123

4321234

Write a program to display this pattern for N=5"""

SOURCE CODE

def pattern(n):

for i in range(1, n + 1):

print(" " * (n - i), end = '')


for j in range(1, i + 1):

print(j, end = '')

for k in range(i - 1, 0, -1):

print(k, end = '')

print()

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

pattern(num)

OUTPUT:

TASK-3: - Define a function isArmstrong(N) to check whether N is an Armstrong or not. If Armstrong,


the function should return 1 otherwise 0. Using the defined function, write a program to display all
Armstrong numbers between 1 and 1000.

def armstrong(n):

def armstrong(n):

s = str(n)

l = []

c = []

for i in range(len(s)):

l.append(int(s[i]))

for i in l:
cube = i ** 3

c.append(cube)

if sum(c) == n:

return 1

else:

return 0

x = int(input("Enter Number: "))

print(armstrong(x))

OUTPUT:

TASK-4: WAPP a Python function to display the Fibonacci sequence up till the nth term

SOURCE CODE:

def Fibonacci(n):

if n < 0:

print("Incorrect input")

elif n == 0:

return 0

elif n == 1 or n == 2:

return 1

else:

return Fibonacci(n-1) + Fibonacci(n-2)

print(Fibonacci(7))

OUTPUT:
TASK – 5:WAP function isPalindrome() to check if a Python function is a palindrome or not.

SOURCE CODE

def isPalindrome(n):

num = str(n)

if num == num[::-1]:

return True

else:

return False

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

print(isPalindrome(num))

OUTPUT:

TASK-6:WAPP to display the roots of a quadratic equation and check if they are real ,imaginary or
equal.

SOURCE CODE:

import math

A=int(input("enter the coeff of x^2"))

B=int(input("enter the coeff of x"))

C=int(input("enter the constant term"))


D=(B**2)-(4*A*C)

d=math.sqrt(D)

r1=(-B+d)/2*A

r2=(-B-d)/2*A

if D < 0:

print("the roots are imaginary")

elif D>0:

print("roots are real")

print("root1 is : ", r1)

print("\nroot2 is :",r2)

elif D==0:

print('roots are equal')

OUTPUT:

TASK-7: Define a Python function HCF(A,B) to calculate and return the HCF of the numbers A and B.
Using this function write a program to check if the 2 user inputted numbers X and Y are co prime or
not

def HCF(a, b):

list1 = []

if a > b:

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

if (a % i == 0 and b % i == 0):

list1.append(i)

else:

for i in range(2, b + 1):


if (a % i == 0 and b % i == 0):

list1.append(i)

if len(list1) > 0:

print(f"These numbers are not co prime. Their HCF is {list1[-1]}")

else:

print("These numbers are co prime. Their HCF is 1")

num1 = int(input("Enter first natural number: "))

num2 = int(input("Enter second natural number: "))

HCF(num1, num2)

OUTPUT

TASK-8: WAPP to calculate income tax on a given user inputted salary .

SOURCE CODE:

while True:

try:

income = int(input("Please enter your taxable income in india: "))

except ValueError:

print("Please enter an acceptable value")

continue

else:
break

if income <= 250000: #2 Lakh 50 thousand

tax = 0

elif income <= 500000: #5 Lakh

tax = (income - 250000) * 0.05

elif income <= 750000: #7 lakh 50 thousand

tax = (income - 500000) * 0.10 + 12500

elif income <= 1000000: #10 Lakh

tax = (income - 750000) * 0.15 + 37500

elif income <= 1250000: #12 lakh 50 thousand

tax = (income - 1000000) * 0.20 + 75000

elif income <= 1500000: #15 lakh

tax = (income - 1250000) * 0.25 + 125000

else:

tax = (income - 1500000) * 0.30 + 187500

print("you owe", tax,'as income tax')

OUTPUT:
TASK-9: Define functions Pow(X,Y) and Factorial(Y) to calculate and return X, and Y! respectively.

Using the defined function, write programs to calculate and display the sum of the following series:

1 + x + x^2 + x^3 ... + x^n."""

SOURCE CODE:

def series(Y,X):

sum = 0

for i in range (X+1):

fact=X**i

sum+=fact

return fact

num1=int(input('enter Y: '))

num2=int(input('enter X: '))

print(series(num1,num2))

OUTPUT:

TASK-10: Define a function SumOfFactors(N) to calculate and return sum of all proper factors of N (all

factors including 1 and excluding the number N itself). Using the defined function, write a

program to check whether a number M is perfect or not.


SOURCE CODE:

def sumOfFactors(n):

list1 = []

for i in range(1, n):

if n % i == 0:

list1.append(i)

return sum(list1)

x = int(input("Enter Number: "))

print(sumOfFactors(x))

if sumOfFactors(x) == x:

print(x,' is a perfect number')

else:

print(x,'is not a perfect number')

OUTPUT

STRING/TUPLE/LIST/DICTIONARY-BASED
PROGRAMS

TASK-11: WAPP to illustrate the difference between append() vs insert() methods and pop() vs
remove() methods when applied on a Python LIST

L=['a','b','c','d','e','f'] print(L) L.append('g')

print("Suppose we append 'g' to the list : ",L)

L.insert(3,'g') print("If we insert 'g' after 'c': ", L)

L.remove('d') print("If we use remove() method to remove


'd' : ", L) print("If we use pop() method : ")

x=L.pop(1) print("The element removed is ", x, "and

the list is : ",L)

OUTPUT:

TASK-12: WAPP to process STACK (LIFO) operations on a Python LIST of numbers.

SOURCE CODE:

stack = []

stack.append('a')

stack.append('b')

stack.append('c')

print('initial elements in stack:')

print(stack)

print('\nElements popped from stack:')

print(stack.pop())

print(stack.pop())

print(stack.pop())

print('\nStack after elements are popped:')

print(stack)
OUTPUT:

TASK-13: WAPP to read a LIST of numbers and create 2 separate LISTs EVEN and ODD

SOURCE CODE:

N=int(input("Enter the number of elements in the list: "))

L=[]

EVEN=[]

ODD=[]

for i in range(1,N+1):

print("Enter element number ",i, end='')

ele=int(input(" : "))

L.append(ele)

for j in L: if

(j%2==0):

EVEN.append(j)

else:

ODD.append(j) print("The list of even

numbers is : ", EVEN) print("The list of odd

numbers is : ", ODD

OUTPUT:
TASK-14: WAPP to read a name and display the. Initial as M.K.G

SOURCE CODE:

NAME=input("Enter a name : ")

L=NAME.split()

print("The initials are: ", end='')

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

print(L[i][0],end='.')

print(" ",L[-1])

OUTPUT:

TASK-15: Write a menu (and function) based program to perform the following tasks on a Python
List

STUDENTS storing names and marks of a few students having the following structure and

implemented as a Stack based on LIFO operations.

A sample List STUDENTS=[['Rudransh',70],['Kapoor',90]]

The tasks are (based on LIFO):

i) Add a new student in the List STUDENTS, name and marks entered by the user

ii) Display all Student’s Names and their Marks from the List STUDENTS

iii) Remove a student from the List of STUDENTS. Also display the content of the removed

student
SOURCE CODE:

STUDENTS=[['Rudransh',70],['Kapoor',90]]

def APPEND():
Name=input('Enter the name of the student :')
Marks=int(input('Enter the marks :'))
STUDENTS.append([Name,Marks])

def DISPLAY():
if len(STUDENTS)==0:
print('underflow')
else:
for i in STUDENTS:
print(i)

def DELETE():
if len(STUDENTS)==0:
print('Underflow!,deletion is not possible')
else:
return STUDENTS.pop()

while True:
print("1. Add Record")

print("2. Delete Record")

print("3. Display Records")

print("4. Exit")
CHOICE=input('Enter your choice : ')
if CHOICE=='1':
APPEND()
elif CHOICE=='2':
DISPLAY()
elif CHOICE=='3':
print(DELETE())
elif CHOICE=='4':
print('Thank you')
break
else:
print('Invalid choice.')

OUTPUT:
TASK 16: WAPP to process QUEUE (FIFO) operations on a Python LIST of names

SOURCE CODE:

queue = []

queue.append('a')
queue.append('b')
queue.append('c')

print("Initial queue")
print(queue)

print("\nElements dequeued from queue")


print(queue.pop(0))
print(queue.pop(0))
print(queue.pop(0))

print("\nQueue after removing elements")


print(queue)

OUTPUT:
TASK 18: WAPP to read a list having 10 names and display only
those that begin with vowels.

SOURCE CODE:

vowels = []

for i in range(1, 11):


names = input("enter names: ")
vowels.append(names)

print("Names which begin with vowels: ")

for names in vowels:


if (names[0].upper() in 'AEIOU'):
print(names)

OUTPUT:

TASK-19: Write a menu (and function) based program to perform the following tasks on a Python List
PERSONS storing name and age of few persons having the following structure and
implemented as a Queue based on FIFO operations.
A sample List PERSONS=[['Rahamat',18],['Rajeev',19],['Amos',17]]

The tasks are (based on FIFO):


i) Add a new person in the List STUDENTS, name and age entered by the user
ii) Display all person’s Names and their Age from the PERSONS List
iii) Remove a person from the List PERSONS. Also, display the content of the removed
person. If removal/deletion is not possible, specify the reasons. """

SOURCE CODE:

RECORDS=[['Raghav',89],['Rohan',90],['Amrita',91]]

def APPEND():
Name=input('Enter the name of the person :')
Age=int(input('Enter the age ( in years):'))
RECORDS.append([Name,Age])

def DISPLAY():
if len(RECORDS)==0:
print('queue is empty')
else:
for i in RECORDS:
print(i[0],i[1])

def DELETE():
if len(RECORDS)==0:
print('queue is empty, deletion not possible...')
else:
return RECORDS.pop(0)

while True:
print('Press: \n 1 to add a new element \n 2 to display \n 3 to remove an element and then display
it \n 4 to EXIT')
CHOICE=input('Enter your choice : ')

if CHOICE=='1':
APPEND()

elif CHOICE=='2':
DISPLAY()

elif CHOICE=='3':
print(DELETE())

elif CHOICE=='4':
print('Thank you')
break

else:
print('Invalid choice.')

OUTPUT:
TASK-20: WAPP to read a List having 10 names and display only those that begin with consonants

SOURCE CODE:
consonants = []

for i in range(1, 11):


names = input("enter names: ")
consonants.append(names)

print("Names which begin with consonants: ")

for names in consonants:


if (names[0].upper() not in 'AEIOU'):
print(names)

OUTPUT:
TASK-21: Write a Python program that accepts a sequence of comma-separated numbers from the
user and generates a list and a tuple with those numbers.

SOURCE CODE:

numbers = input("Input some comma seprated numbers : ")

list = numbers.split(",")

tuple = tuple(list)

print('List : ',list)

print('Tuple : ',tuple)

OUTPUT:

TASK-22: WAPP to show names of people over 25 in a given tuple of tuples AGES.

SOURCE CODE:

AGES=()

L=[]

N=int(input('enter no. of names: '))

for i in range (N):

name=input('enter names and ages seperated by spaces:')

a=name.split()

L.append(a)

for j in L:

b=int(j[1])

if (b > 25):

AGES+=(j[0],)
print(AGES)

OUTPUT:

TASK-23: WAPP to print the sum of tuple elements of a tuple (23,45,12,11,13,45,67)

SOURCE CODE:

tuple1=(23,45,12,11,13,45,67)

print('The original tuple is :' + str(tuple1))

sum1=sum(list(tuple1))

print('The sum of all tuple elements is : ' +str(sum1))

OUTPUT:

TASK 24: WAPP to join/merge/concatenate the following 2 dictionaries and create a new dictionary.

Dict1={1:’Rudransh’,2:’Ananya’}

Dict2={6:’Arnav’,4:’Saksham’}

New Dictionary={1:’Rudransh’,2:’Ananya’ ,6:’Arnav’, 4:’Saksham’}

SOURCE CODE:

dict1={1:'Rudransh',2:'Ananya'}

dict2={6:'Arnav',4:'Saksham'}

print('first dictionary is :' )


print(dict1)

print('second dictionary is :' )

print(dict2)

dict3={}

for i in (dict1,dict2):

dict3.update(i)

print('updated list:',dict3)

OUTPUT:

TASK-25: Define a function GRADES(EMPLOYEES) to accept a Python dictionary EMPLOYEES as a

formal argument and creates and returns two separate dictionaries GradeA and GradeB

depending upon whether the values(Salary) are more than 25000 or not as explained below:

A sample Dictionary EMPLOYEES = {'John':18000,'Rahim':24000,'Anita':31000}

The separated Dictionaries are:

GradeA = {'Anita':31000}

GradeB = {'John':18000,'Rahim':24000}

The tasks are:

i) Add a new entry in the Dictionary EMPLOYEES, entered by the user

ii) Display all entries stored in the Dictionary EMPLOYEES

iii) Separate the Dictionary EMPLOYEES using the defined function and display the two

newly created Dictionaries GradeA and GradeB."""

SOURCE CODE:

def grades(employee):

gradeA = {}
gradeB = {}

for i in employee:

if employee[i] > 25000:

gradeA[i] = employee[i]

else:

gradeB[i] = employee[i]

return gradeA, gradeB

employees = {'John': 18000, 'Rahim': 24000, 'Anita': 31000}

new_employee = input("Enter Name: ")

new_salary = int(input("Enter Salary: "))

employees[new_employee] = new_salary

print(f"The employees are: {employees}")

print(f"Grade A and Grade B employees respectively are: {grades(employees)}")

OUTPUT:

TASK-26: Write a method in python to read a text file ‘poem.txt’ line by line and display the same on
the screen.

SOURCE CODE:

def read():

f=open('poem.txt','r')
while True:

a=f.readlines()

if a==' ':

break

else:

print(a)

break

read()

OUTPUT:

TASK-27: Write a method in Python to read lines from a text file ‘poem.txt’ and display those lines
starting with the alphabet A.

SOURCE CODE:

def read():

f=open('poem.txt','r')

lines=f.readlines()

print(lines)

for i in lines:

if i[0]=='A':

print(i)

read()

OUTPUT:
TASK 28: Write a method in Python BIGLINES[] to read lines from a file ‘poem.txt’ and display those
lines that are bigger than 50 characters

SOURCE CODE:

def BIGLINES():

f=open('poem.txt','r')

lines=f.readlines()

for k in lines:

print(k)

for i in lines:

if len(i)>=50:

print(i)

BIGLINES()

OUTPUT:

TASK-29: Write a method in Python to count the total number of words in a text file ‘poem.txt’.

SOURCE CODE:

def COUNTWORDS():
f=open('poem.txt','r')
count=0
text=f.read()
print(text)
words=text.split()
for i in words:
count+=1
print('Total no. of words in the given text file are=',count)

COUNTWORDS()

OUTPUT:

TASK 30: To create a menu-based program to perform operations on a text file, containing a
paragraph

SOURCE CODE:
def APPEND():
f=open('poem.txt','a')
S=input('Enter the text you want to add :')
f.write(S)
f.close()

def REPLACE(initial,final):
f=open('poem.txt','r')
S=f.read().split()
f.close()
text=''

for word in S:
if word==initial:
text+=' '+ final
else:
text+=' '+word
print(text)
F2=open('poem.txt','w')
F2.write(text)
F2.close()

def FREQUENCY(WORD):
F=open('poem.txt','r')
count=0
S=F.read().split()
for i in S:

if i.upper()==WORD.upper():
count+=1
print('The frequency of the word is', count)
F.close()

def DISPLAY():
F=open('poem.txt','r')
S=F.readlines()
for i in S:
print(i)
F.close()

while True:
print('== MAIN MENU ==')
print('1. Append')
print('2. Display')
print('3. Replace a word')
print('4. count the frequency of a word' )
print('5. Quit')
Choice=input("Your Choice: ")
if Choice=='1':
APPEND()
elif Choice=='2':
DISPLAY()
elif Choice=='3':
initial=input('Enter the old word to be replaced : ')
final= input('Enter the new word :')
REPLACE(initial,final)
elif Choice=='4':
WORD=input('Enter the word whose frequency you would like to know :')
FREQUENCY(WORD)
elif Choice=='5':
print('Thank you!')
break
else:
print('Invalid choice...')

OUTPUT:

1)
TASK 31: Take a sample of ten phishing e-mails (or any text file) and find most commonly occurring
word(s)

SOURCE CODE:

def phishing():
D={}
F=open('poem.txt','r')

for line in F.readlines():


for word in line.split():
if word in D.keys():
D[word]+=1
else:
D[word]=1

max1=max(list(D.values()))
emails=[]
for i in D.keys():
if D[i]==max1:
emails.append(i)
F.close()
return emails
print('The list most commonly occuring words is :', phishing())
OUTPUT:

TASK-32: Create a menu-based binary file ‘Bloodbank.dat ’ to carry out operations such as
append/search/display/modify/update/delete in the given binary file .

SOURCE CODE:

mport pickle

def Append():
BlockRecords=[]
while True:
DID=input("Donor's ID: ")
Name=input("Donor's Name: ")
BGroup=input("Donor's Blood Group: ")
aRecord=[DID,Name,BGroup]
BlockRecords.append(aRecord) #[[,,],[,,],[,,]] [[,,],[,,]]
Response=input("Do you want to add more? ")
if Response[0].upper()!='Y':
break

F1=open('BloodBank.dat','ab')
pickle.dump(BlockRecords,F1)
F1.close()

def Display():
try:
F2=open('BloodBank.dat','rb')
while True:
try:
BlockRecords=pickle.load(F2)
for aRecord in BlockRecords:
print(aRecord[0],aRecord[1],aRecord[2])
except:
F2.close()
break
except:
print('File opening problem!')
def Search(BG):
Counter=0
try:
F2=open('BloodBank.dat','rb')
while True:
try:
BlockRecords=pickle.load(F2)
for aRecord in BlockRecords:
if BG.upper()==aRecord[2].upper():
Counter+=1
print(aRecord[0],aRecord[1],aRecord[2])
except:
F2.close()
break

except:
print('File opening problem!')

print('Total ',Counter,' record(s) found!')

def Modify(ID):
NewRecords=[]
Flag=0
try:
F2=open('BloodBank.dat','rb')
while True:
try:
BlockRecords=pickle.load(F2)
for aRecord in BlockRecords:
if ID.upper()==aRecord[0].upper():
print(aRecord[0],aRecord[1],aRecord[2])
aRecord[2]=input("ENter the new value: ")
Flag+=1

NewRecords.append(aRecord)
except:
F2.close()
break
F1=open('BloodBank.dat','wb')
pickle.dump(NewRecords,F1)
F1.close()

except:
print('File opening problem!')

print('Total ',Flag,' record(s) updated!')


def Delete(ID):
NewRecords=[]
Flag=0
try:
F2=open('BloodBank.dat','rb')
while True:
try:
BlockRecords=pickle.load(F2)
for aRecord in BlockRecords:
if ID.upper()==aRecord[0].upper():
print(aRecord[0],aRecord[1],aRecord[2])
Flag+=1
else:
NewRecords.append(aRecord)
except:
F2.close()
break
F1=open('BloodBank.dat','wb')
pickle.dump(NewRecords,F1)
F1.close()

except:
print('File opening problem!')

print('Total ',Flag,' record(s) deleted!')

while True:
print('== MAIN MENU ==')
print('1. Search')
print('2. Display')
print('3. Append')
print('4. Update')
print('5. Delete')
print('6. Quit')
Choice=input("Your Choice: ")
if Choice=='1':
BG=input("Enter the Blood Group you want to search: ")
Search(BG)
elif Choice=='2':
Display()
elif Choice=='3':
Append()
elif Choice=='4':
ID=input("Enter the Donor's ID you want to update: ")
Modify(ID)
elif Choice=='5':
ID=input("Enter the Donor's ID you want to delete: ")
Delete(ID)
elif Choice=='6':
print('Thank you!')
break
else:
print('Invalid Choice! Try Again.')

OUTPUT:

TASK 33: Create a binary file to write the record of a student such as rno, marks, and name, and
display the same.

SOURCE CODE:
import pickle
def write():
f=open('BinaryRecord.dat','wb')
record=[]
count = 0
while True:
rno=int(input('enter rno: '))

name=input('enter name: ')


marks=int(input('enter marks :'))
data=[rno,name,marks]
record.append(data)
count=count +1
choice=input('Do you want to enter more records? (y/n)')
if choice=='n':
break
pickle.dump(record,f)

def read():
f=open('BinaryRecord.dat','rb')
a=pickle.load(f)
for i in a:
rno=i[0]
name=i[1]
marks=i[2]
print(rno,name,marks)

while True:
print('== MAIN MENU ==')
print('1. write')
print('2. read')
print('3. Quit')
Choice=input("Your Choice: ")
if Choice=='1':
write()
elif Choice=='2':
read()
elif Choice=='3':
print('Thank you!')
break
else:
print('Invalid Choice! Try Again.')

OUTPUT:
Task 34: Write a function to search and display all the names of the students whose marks are
between 50 and 70.

SOURCE CODE:

import pickle
def write():
f=open('BinaryRecord.dat','wb')
record=[]
count = 0
while True:
rno=int(input('enter rno: '))
name=input('enter name: ')
marks=int(input('enter marks :'))
data=[rno,name,marks]
record.append(data)
count=count +1
choice=input('Do you want to enter more records? (y/n)')
if choice=='n':
break
pickle.dump(record,f)

def read():
f=open('BinaryRecord.dat','rb')
a=pickle.load(f)
for i in a:
rno=i[0]
name=i[1]
marks=i[2]
print(rno,name,marks)
f.close()

def search():
f=open('BinaryRecord.dat','rb')
a=pickle.load(f)
print('Displaying marks in the range of 50 and 70 :')
for i in a:
if i[2]>50 and i[2]<70:
print(i)

#write()
read()
search()

OUTPUT:

TASK 35:Write a code that reads from a file “sales.dat” which has the following information
[itemcode, amount] and read from the file and find the sum of the amount.

SOURCE CODE:

import pickle
F = open ("Binaryfile.dat", "rb")
sum = 0
while True:
try:
a = pickle.load(F)
sum = sum + a[1]
except:
break

print (sum)
F.close()

TASK-36: Create a binary file with name and roll number. Search for a given roll number and display
the name, if not found display appropriate message

SOURCE CODE:

import pickle
def append():
F=open('BinaryFile.dat','wb')
Allrec=[]
while True:
Name=input('Enter the name :')
Roll_no = int(input('Enter the roll no. :'))
Allrec.append([Name, Roll_no])
choice=input('Are there more entries to be made? (Y/N)')
if choice.upper()=='N':
break
pickle.dump(Allrec,F)
F.close()
print('Data successfully written ')

def SEARCH():
F=open('Binaryfile.dat','rb')
R=int(input('Enter the roll no. you want to search for '))
found=0
for rec in pickle.load(F):
if rec[1]==R:
found=1
print('Record successfully found')
print(rec[0])
F.close()
if found==0:
print('Record not found')

print('Creating the binary file :')


append()
print('search')
SEARCH()

OUTPUT:

TASK-37:WAPP to
a) create/append a CSV file phone.csv having names and phone numbers of a few persons.
b) Read/Search and display the content of the CSV file phone.csv.

SOURCE CODE:
import csv
outfile=open('phone.csv','a')
R=csv.writer(outfile)
while True:
name =input('enter name:')
Phone=int(input('enter phone number:'))
Data=[name,Phone]
R.writerow(Data)
choice=input('Do you want to enter any more records (Y/N):')
if choice =='N' or choice=='n':
break

outfile.close()

infile=open('phone.csv','r',newline='\r\n')
list1=csv.reader(infile)
for aRow in list1:
print(aRow[0],'\t',aRow[1])

infile.close()

OUTPUT:

TASK 38: Write a Python program to read each row from a given csv file and print a list of strings.

SOURCE CODE:

import csv

def read(filename):
rows = []
with open(filename, 'r') as file:
csv_reader = csv.reader(file)
for row in csv_reader:
rows.append(row)
return rows

def print_list_of_strings(rows):
for row in rows:
print(', '.join(row))

filename = 'phone.csv'
rows = read(filename)
print_list_of_strings(rows)

OUTPUT:

TASK 39: Create a csv file with name and roll number. Search for a given roll number and display
the name, if not found display appropriate message'''

SOURCE CODE:

import csv

def CREATE():
F=open('ClassRec.csv','w',newline='')
Allrec=[]
while True:
Name=input('Enter the name :')
Roll_no = input('Enter the roll no. :')
Allrec.append([Name, Roll_no])
choice=input('Are there more entries to be made? (Y/N)')
if choice.upper()=='N':
break
csvwriter=csv.writer(F)
csvwriter.writerow([ 'Name', 'Roll No.'])
csvwriter.writerows(Allrec)
F.close()
print('Data successfully written ')

def SEARCH():
F=open('ClassRec.csv','r')
R=input('Enter the roll no. you want to search for ')
found=0
Allrec=csv.reader(F)
for rec in Allrec:
if rec[1]==R:
found=1
print('Record successfully found')
print(rec[0])
F.close()
if found==0:
print('Record not found')

CREATE()

SEARCH()

OUTPUT:

TASK 40: To create a menu-based program for an address book (in a CSV FILE), to the store the
following details : PID(Person's id), Name, address, phone number, and email id

1. To append a new record

2. To display all the records

3. search a person by name


4. modify the address by pid

5. delete a record by pid '''

SOURCE CODE:

import csv

def Append():
Allrec=[]

while True:

PID=input("ID :")

Name=input("Name: ")
Add=input("Address :")

Ph=input('Phone number :')

Em=input('Enter the email id :')


rec=[PID,Name,Add,Ph, Em]

Allrec.append(rec)

choice=input("Do you want to add more? (Y/N)")

if choice=='N':
break

F=open('addbook.csv','a', newline='\r\n')
writerobj=csv.writer(F)

writerobj.writerows(Allrec)

F.close()

def Display():

F=open('addbook.csv','r', newline='\r\n')
Allrec=csv.reader(F)

for rec in Allrec:


print(rec[0],rec[1],rec[2], rec[3], rec[4])

F.close()
def Search(NAME):
found=0

F=open('addbook.csv','r', newline='\r\n')

Allrec=csv.reader(F)
for rec in Allrec:

if NAME.upper()==rec[1].upper():

found+=1
print(rec[0],rec[1],rec[2],rec[3],rec[4])

F.close()

if found==0:

print('Record not found...')

def Modify(PID):

NewRecords=[]
F=open('addbook.csv','r', newline='\r\n')

Allrec=csv.reader(F)
for rec in Allrec:
if PID.upper()==rec[0].upper():

print(rec[0],rec[1],rec[2], rec[3],rec[4])
rec[2]=input("Enter the new address: ")

NewRecords.append(rec)

F.close()
F1=open('addbook.csv','w', newline='\r\n')

writerobj=csv.writer(F1)

writerobj.writerows(NewRecords)
F1.close()
def Delete(PID):

NewRecords=[]
F=open('addbook.csv', newline='\r\n')

Allrec=csv.reader(F)

for rec in Allrec:


if PID.upper()==rec[0].upper():

print(rec[0],rec[1],rec[2],rec[3],rec[4])

else:
NewRecords.append(rec)

F.close()

F1=open('addbook.csv','w', newline='\r\n')

writerobj=csv.writer(F1)
writerobj.writerows(NewRecords)

F1.close()

while True:
print('== MAIN MENU ==')

print('1. Search')
print('2. Display')
print('3. Append')

print('4. Update')

print('5. Delete')
print('6. Quit')

Choice=input("Your Choice: ")

if Choice=='1':
NAME=input("Enter person's Name you want to search for: ")
Search(NAME)
elif Choice=='2':

Display()
elif Choice=='3':
Append()

elif Choice=='4':

PID=input("Enter the person's ID whose address you want to update: ")


Modify(PID)

elif Choice=='5':

PID=input("Enter the person's ID whose record you want to delete: ")


Delete(PID)

elif Choice=='6':

print('Thank you!')

break
else:

print('Invalid Choice! Try Again.')

OUTPUT:
TASK 41-45:
SOURCE CODE + OUTPUT:
TASK 46: Create a new table exam in the database school storing roll number ,name and marks of a
few students using python mysql connectivity.

SOURCE CODE:

OUTPUT:

TASK-47:To display the contents of an existing table school using Python MySQL connectivity.

SOURCE CODE:
OUTPUT:

TASK-48: To display or search all matched rows in a table school using python MySQL connectivity.

SOURCE CODE:
OUTPUT:

TASK-49: To update a row in the table student and displaying it using python MySQL connectivity

SOURCE CODE:
OUTPUT:

TASK-50: Delete a row from table student using python MySQL connectivity and display the same.

SOURCE CODE:
OUTPUT:

SQL OUTPUT:

You might also like