CS Program File-23
CS Program File-23
CS Program File-23
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:
else:
leap_year()
OUTPUT:
TASK-2: Define a function Pattern(N) to display the following pattern when N=4:
212
32123
4321234
SOURCE CODE
def pattern(n):
print()
pattern(num)
OUTPUT:
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
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:
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
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
d=math.sqrt(D)
r1=(-B+d)/2*A
r2=(-B-d)/2*A
if D < 0:
elif D>0:
print("\nroot2 is :",r2)
elif D==0:
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
list1 = []
if a > b:
if (a % i == 0 and b % i == 0):
list1.append(i)
else:
list1.append(i)
if len(list1) > 0:
else:
HCF(num1, num2)
OUTPUT
SOURCE CODE:
while True:
try:
except ValueError:
continue
else:
break
tax = 0
else:
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:
SOURCE CODE:
def series(Y,X):
sum = 0
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
def sumOfFactors(n):
list1 = []
if n % i == 0:
list1.append(i)
return sum(list1)
print(sumOfFactors(x))
if sumOfFactors(x) == x:
else:
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
OUTPUT:
SOURCE CODE:
stack = []
stack.append('a')
stack.append('b')
stack.append('c')
print(stack)
print(stack.pop())
print(stack.pop())
print(stack.pop())
print(stack)
OUTPUT:
TASK-13: WAPP to read a LIST of numbers and create 2 separate LISTs EVEN and ODD
SOURCE CODE:
L=[]
EVEN=[]
ODD=[]
for i in range(1,N+1):
ele=int(input(" : "))
L.append(ele)
for j in L: if
(j%2==0):
EVEN.append(j)
else:
OUTPUT:
TASK-14: WAPP to read a name and display the. Initial as M.K.G
SOURCE CODE:
L=NAME.split()
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
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("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)
OUTPUT:
TASK 18: WAPP to read a list having 10 names and display only
those that begin with vowels.
SOURCE CODE:
vowels = []
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]]
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 = []
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:
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=[]
a=name.split()
L.append(a)
for j in L:
b=int(j[1])
if (b > 25):
AGES+=(j[0],)
print(AGES)
OUTPUT:
SOURCE CODE:
tuple1=(23,45,12,11,13,45,67)
sum1=sum(list(tuple1))
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’}
SOURCE CODE:
dict1={1:'Rudransh',2:'Ananya'}
dict2={6:'Arnav',4:'Saksham'}
print(dict2)
dict3={}
for i in (dict1,dict2):
dict3.update(i)
print('updated list:',dict3)
OUTPUT:
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:
GradeA = {'Anita':31000}
GradeB = {'John':18000,'Rahim':24000}
iii) Separate the Dictionary EMPLOYEES using the defined function and display the two
SOURCE CODE:
def grades(employee):
gradeA = {}
gradeB = {}
for i in employee:
gradeA[i] = employee[i]
else:
gradeB[i] = employee[i]
employees[new_employee] = new_salary
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')
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!')
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!')
except:
print('File opening problem!')
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: '))
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')
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
SOURCE CODE:
import csv
def Append():
Allrec=[]
while True:
PID=input("ID :")
Name=input("Name: ")
Add=input("Address :")
Allrec.append(rec)
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)
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:
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)
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')
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':
elif Choice=='5':
elif Choice=='6':
print('Thank you!')
break
else:
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: