12 Cs Lab Progrms 1 20
12 Cs Lab Progrms 1 20
No:1
DATE:
Arithmetic operations
AIM:
To write a menu driven python program to perform Arithmetic operations based on the user’s
choice.
SOURCE CODE:
def addition(a, b):
sum = a + b
print(a, "+", b, "=", sum)
def subtraction(a, b):
difference = a - b
print(a, "-", b, "=", difference)
def multiplication(a, b):
product = a * b
print(a, "*", b, "=", product)
def divide(a, b):
quotient = a / b
remainder = a % b
print("Quotient of", a, "/", b, "=", quotient)
print("Remainder of", a, "%", b, "=", remainder)
print("WELCOME TO CALCULATOR")
while True:
print("\nChoose the operation to perform:")
print("1. Addition of two numbers")
print("2. Subtraction of two numbers")
print("3. Multiplication of two numbers")
print("4. Division of two numbers")
print("5. Exit")
choice = int(input("\nEnter your Choice: "))
if choice == 1:
print("\nAddition of two numbers")
a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))
addition(a,b)
elif choice == 2:
print("\nSubtraction of two numbers")
a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))
subtraction(a,b)
elif choice == 3:
print("\nMultiplication of two numbers")
a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))
multiplication(a,b)
elif choice == 4:
print("\nDivision of two numbers")
a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))
divide(a,b)
elif choice == 5:
print("Thank You! Bye.")
break
else:
print("Invalid Input! Please, try again.")
Result:
The above output has been verified in the terminal.
SAMPLE OUTPUT
WELCOME TO CALCULATOR
Choose the operation to perform:
1. Addition of two numbers
2. Subtraction of two numbers
3. Multiplication of two numbers
4. Division of two numbers
5. Exit
Enter your Choice: 1
Addition of two numbers
Enter the first number: 5
Enter the second number: 5
5 + 5 = 10
Choose the operation to perform:
1. Addition of two numbers
2. Subtraction of two numbers
3. Multiplication of two numbers
4. Division of two numbers
5. Exit
Enter your Choice: 2
Subtraction of two numbers
Enter the first number: 5
Enter the second number: 5
5-5=0
Choose the operation to perform:
1. Addition of two numbers
2. Subtraction of two numbers
3. Multiplication of two numbers
4. Division of two numbers
5. Exit
Enter your Choice: 3
Multiplication of two numbers
Enter the first number: 5
Enter the second number: 5
5 * 5 = 25
Choose the operation to perform:
1. Addition of two numbers
2. Subtraction of two numbers
3. Multiplication of two numbers
4. Division of two numbers
5. Exit
Enter your Choice: 4
Division of two numbers
Enter the first number: 25
Enter the second number: 5
Quotient of 25 / 5 = 5.0
Remainder of 25 % 5 = 0
Choose the operation to perform:
1. Addition of two numbers
2. Subtraction of two numbers
3. Multiplication of two numbers
4. Division of two numbers
5. Exit
Enter your Choice: 5
Thank You! Bye.
P.NO.2
DATE
LIST SWAP
A List contains the following elements N1=[3,25,13,6,35,8,14,45]
Write a user defined function swap ( ) that takes in lst as a parameter and swaps the content with
the next value divisible by 5 so that the resultant list will look like:
[25, 3, 13, 35, 6, 8, 45, 14]
AIM:
To write a user defined function swap ( ) that takes in lst as a parameter and swaps the content with
the next value divisible by 5
SOURCE CODE:
Result:
The above output has been verified in the terminal.
SAMPLE OUTPUT:
P.NO.3
DATE
STRING OPERATIONS
AIM:
To write a menu driven program in python using user defined functions to take string as input and
(i) To check whether the given string is palindrome or not.
(ii) To count number of occurrences of a given character
SOURCE CODE:
def palindrome(s):
rev=s[::-1]
if rev==s:
print("The String is palindrome")
else:
print("The string is not a palindrome")
def Count(st,choice):
c=st.count(ch)
return c
#Main program
while True:
print("Menu")
print("1.palidrome")
print("2.To count number of occurrences of a given character")
print("3. Exit")
opt=int(input("Enter your choice:"))
if opt==1:
s=input("enter the string:")
palindrome(s)
elif opt==2:
st=input("Enter the string:")
ch=input("Enter a character")
cnt=Count(st,ch)
print("The character",ch,"is present in",st,"is",cnt,"times")
elif opt==3:
break
else:
print("Invalid Choice")
Result:
The above output has been verified in the terminal.
SAMPLE OUTPUT:
Menu
1.palidrome
2.To count number of occurrences of a given character
3. Exit
Enter your choice:1
enter the string:MALAYALAM
The String is palindrome
Menu
1.palidrome
2.To count number of occurrences of a given character
3. Exit
Enter your choice: 2
Enter the string: GOOD MORNING
Enter a character O
The character O is present in GOOD MORNING is 3 times
Menu
1.palidrome
2.To count number of occurrences of a given character
3. Exit
Enter your choice:3
P.NO.4
DATE:
TO SHOW GRADES USING DICTIONARY
AIM:
To write a python program that uses a function showGrades(s) which takes the dictionary S as an
argument. The dictionary, S contains Name:[Eng,Math,CS] as key value pairs.The function displays
the corresponding grades obtained by the student according to the following grading rules:
Average of Eng,Math,CS Grade
>=90 A
<90 but >=60 B
<60 C
SOURCE CODE:
Result:
The above output has been verified in the terminal.
SAMPLE OUTPUT:
David 270 90.0 – A
P.NO. 5
DATE:
DICTIONARY –CREATE AND UPDATE
AIM:
To write a python script to print a dictionary where the keys are numbers between 1 and 15(both
included) and the values are square of keys. Also write a function search () that takes in the
dictionary d as parameter and searches for a particular key, if found returns the corresponding
value, if not found, an error message will displayed.
Sample dictionary
{1:1,2:4,3:9,4:16,…15:225}
SOURCE CODE:
Result:
The above output has been verified in the terminal.
SAMPLE OUTPUT:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11: 121, 12: 144, 13: 169, 14: 196, 15:
225}
1.Search for a value
2.Exit
Enter your choice:1
Enter a key-value to search4
key 4 is found, the value is 16
1.Search for a value
2.Exit
Enter your choice:2
P.NO.6
DATE:
DISPLAY SENTENCE
AIM:
To create a python program to read a Text file and Display every sentence in a Separate line.
SOURCE CODE:
Result:
Thus, the above Python program is executed successfully and the output is verified.
SAMPLE OUTPUT:
STORY.TXT
PYTHON OUTPUT:
P.NO.7
DATE:
NUMBER OF VOWELS/CONSONANTS/LOWER CASE/ UPPER CASE CHARACTERS.
AIM:
To write a Python Program to read a text file "Story.txt" and displays the number of Vowels/
Consonants/ Lowercase / Uppercase/characters in the file.
SOURCE CODE:
Result:
Thus, the above Python program is executed successfully and the output is verified.
STORY.TXT
DATE:
COPY LINES OF A TEXT FILE INTO AN ANOTHER TEXT FILE
AIM:
To write a python program to read lines from a text file "Sample.txt" and copy those lines into
another file which are starting with an alphabet 'a' or 'A'.
SOURCE CODE:
Result:
Thus, the above Python program is executed successfully and the output is verified.
SAMPLE OUTPUT:
SAMPLE.TXT
NEW.TXT
PYTHON OUTPUT:
P.NO.9
Date:
CREATE AND SEARCH RECORDS IN BINARY FILE
AIM:
To write a Python Program to Create a binary file with roll number and name.
Search for a given roll number and display the name, if not found display
appropriate message.
SOURCE CODE:
import pickle
def Create():
f=open("students.dat",'ab')
opt='y'
while opt=='y':
Rno=int(input("Enter Roll number:"))
Name=input("Enter Name:")
l=[Rno,Name]
pickle.dump(l,f)
opt=input("Do you want to add another record:(y/n)")
f.close()
def search():
f1=open("students.dat",'rb')
no=int(input("Enter roll no. to be searched for:"))
found=False
try:
while True:
s=pickle.load(f1)
if s[0]==no:
print("The searched roll no is",s)
found=1
break
else:
print("The searched roll no not found")
except:
f.close()
#main program
Create()
search()
Result:
Thus, the above Python program is executed successfully and the output is
verified.
SAMPLE OUTPUT:
P.NO: 10
DATE:
CREATE AND UPDATE/MODIFY RECORDS IN BINARY FILE
AIM:
To write a Python Program to Create a binary file with roll number, name,
mark and update/modify the mark for a given roll number.
SOURCE CODE:
import pickle,os
def Create( ):
f=open("Marks.dat",'ab')
opt='y'
while opt=='y':
Rno=int(input("Enter roll number:"))
Name=input("Enter Name:")
Mark=int(input("Enter Marks:"))
l=[Rno,Name,Mark]
pickle.dump(l,f)
opt=input("Do you want to add more record:(y/n)")
f.close()
def Update( ):
f1=open("Marks.dat",'rb')
f2=open("newmarks.dat",'wb')
no=int(input("Enter Roll no to modify mark:"))
found=False
try:
while True:
s=pickle.load(f1)
if s[0]==no:
print("The searched Roll no is found and details are",s)
s[2]=int(input("Enter New mark to be update:"))
pickle.dump(s,f2)
print("Mark updated successfully and details are",s)
found=True
break
except EOFError:
f1.close()
f2.close()
os.remove("Marks.dat")
os.rename("newmarks.dat", "Marks.dat")
if found==False:
print("the roll no not available")
Create( )
Update( )
Result:
Thus, the above Python program is executed successfully and the output is
verified.
SAMPLE OUTPUT:
P.NO:11
DATE:
AIM: To write a Python program Create a CSV file to store Empno, Name,
Salary and search any Empno and display Name, Salary and if not found display
appropriate message.
SOURCE CODE:
import csv
def create():
f=open("Emp.csv",'a',newline='')
w=csv.writer(f)
opt='y'
while opt=='y':
no=int(input("Enter Employee Number:"))
name=input("Enter Employee Name:")
sal=float(input("Enter Employee salary:"))
l=[no,name,sal]
w.writerow(l)
opt=input("Do you want to continue(y/n):")
f.close()
def search():
f=open("Emp.csv",'r',newline='\r\n')
no=int(input("Enter Employee number to search:"))
found=0
row=csv.reader(f)
for data in row:
if data[0]==str(no):
print("\n Employee details are:")
print("========================")
print("Name:",data[1])
print("Salary:",data[2])
print("========================")
found=1
break
if found ==0:
print("The searched Employee number is not found")
f.close()
#Main program
create()
search()
Result:
Thus, the above Python program is executed successfully and the output is
verified.
SAMPLE OUTPUT:
SOURCE CODE:
import csv
def readcsv():
f=open("marks.csv",newline="\r\n")
r=csv.reader(f)
for data in r:
print(data)
def writecsv():
f=open("marks.csv",'w')
writer=csv.writer(f)
opt='y'
while opt=='y':
rno=int(input("Enter the roll no:"))
name=input("Enter the name:")
marks=float(input("Enter the marks:"))
l=[rno,name,marks]
writer.writerow(l)
opt=input("Do you want to continue (y/n)?:")
f.close()
while True:
print("Press 1 to read data")
print("Press 2 to write data")
print("Press 3 to exit")
a=int(input("Enter your choice between 1 to 3:"))
if a==1:
readcsv()
elif a==2:
writecsv()
else:
break
Result:
Thus, the above Python program is executed successfully and the output is
verified.
SAMPLE OUTPUT:
Write a python program to maintain book details like book code, book title
and price using stacks data structures? (Implement push (), pop () ,peek ()
and traverse () functions)
AIM: To write a python program to maintain book details like book code,
book title and price using stacks data structures
Result:
Thus, the above Python program is executed successfully and the output is
verified.
SAMPLE OUTPUT:
1. Push
2. Pop
3.peek
4. Traversal
5. Exit
Enter your choice 1
Enter bcode 101
Enter btitle computer
Enter price 200
1. Push
2. Pop
3.peek
4. Traversal
5. Exit
Enter your choice 1
Enter bcode 102
Enter btitle physics
Enter price 100
1. Push
2. Pop
3.peek
4. Traversal
5. Exit
Enter your choice 2
poped element is
bcode 102 btitle physics price 100
1. Push
2. Pop
3.peek
4. Traversal
5. Exit
Enter your choice 3
the top of the book stack is : ('101', 'computer', '200')
1. Push
2. Pop
3.peek
4. Traversal
5. Exit
Enter your choice 4
('101', 'computer', '200')
1. Push
2. Pop
3.peek
4. Traversal
5. Exit
Enter your choice 5
End
P.NO.14
STACK OPEATIONS WITH CONDITIONS
Write a python program using function PUSH (Arr), where Arr is a list of
numbers. From this list push all numbers divisible by 5 into a stack
implemented by using a list. Display the stack if it has at least one element,
otherwise display appropriate error message.
AIM:
To write a python program using function PUSH (Arr), where Arr is a list of
numbers. From this list push all numbers divisible by 5 into a stack
implemented by using a list. Display the stack if it has at least one element,
otherwise display appropriate error message.
SOURCE CODE:
def push(Arr,item):
if item%5==0:
Arr.append(item)
def pop(Arr):
if Arr==[]:
print("No item found")
else:
print("The deleted element:")
return Arr.pop()
def show():
if Arr==[]:
print('No item found')
else:
top=len(Arr)-1
print("The stack elements are:")
for i in range(top,-1,-1):
print(Arr[i])
#Main program
Arr=[]
top=None
while True:
print('****** STACK IMPLEMENTATION USING LIST ******')
print('1: PUSH')
print('2: pop')
print('3: Show')
print('0: Exit')
ch=int(input('Enter choice:'))
if ch==1:
val=int(input('Enter no to push:'))
push(Arr,val)
elif ch==2:
res=pop(Arr)
print(res)
elif ch==3:
show()
elif ch==0:
print('Bye')
break
Result:
Thus, the above Python program is executed successfully and the output is
verified.
AIM:
SOURCE CODE:
def push(stk,d):
for i in d:
if d[i]>70:
stk.append(i)
def disp():
if stk==[]:
print("stack is empty")
else:
top=len(stk)-1
for i in range(top,-1,-1):
print(stk[i])
stk=[]
d={}
print("performing stack operation using Dictionary")
while True:
print()
print("1.push")
print("2.disp")
print("0.exit")
if opt==1:
push(stk,d)
elif opt==2:
disp()
elif opt==0:
print('Bye')
break
Result:
Thus, the above Python program is executed successfully and the output is
verified.
SAMPLE OUTPUT:
performing stack operation using Dictionary
1.push
2.disp
0.exit
Enter your choice:1
Enter the mark of ramesh:99
Enter the mark of Umesh:76
Enter the mark of Vishal:56
Enter the mark of Khushi:90
Enter the mark of Ishika:95
1.push
2.disp
0.exit
Enter your choice:2
The stack elements are:
Ishika
Khushi
Umesh
Ramesh
1.push
2.disp
0.exit
Enter your choice:
P.NO:16
DATE:
DISPLAY MARKS FROM MYSQL
AIM:
To create a python program to integrate mysql with python to display the
avgmarks greater than 75
SOURCE CODE:
Result:
Thus, the above Python program is executed successfully and the output is
verified.
SQL Table
Output:
P.NO: 17
DATE
INSERT AND DISPLAY USING PYTHON AND MYSQL
AIM:
To write a Python Program to integrate MYSQL with Python by inserting
records to Emp table and display the records.
SOURCE CODE:
Result:
Thus, the above Python program is executed successfully and the output is
verified.
SAMPLE OUTPUT:
Python Executed Program Output:
SQL OUTPUT:
P.NO: 18
SEARCH A RECORD IN MYSQL AND DISPLAY USING PYTHON
AIM:
To write a Python Program to integrate MYSQL with Python to search an
Employee using EMPID and display the record if present in already existing
table EMP, if not display the appropriate message.
SOURCE CODE:
Result:
Thus, the above Python program is executed successfully and the output is
verified.
SAMPLE OUTPUT:
Python Executed Program Output:
RUN -1:
Run – 2:
SQL OUTPUT:
OUTPUT -1:
OUTPUT -2:
P.NO: 19
UPDATE A RECORD IN MYSQL USING PYTHON
AIM:
To write a Python Program to integrate MYSQL with Python to search an
Employee using EMPID and update the Salary of an employee if present in
already existing table EMP, if not display the appropriate message.
SOURCE CODE:
Result:
Thus, the above Python program is executed successfully and the output is
verified.
SAMPLE OUTPUT:
Python Executed Program Output:
RUN -1:
Run -2:
SQL OUTPUT:
P.NO: 20
DATE:
DETELTING A RECORD IN MYSQL USING PYTHON
AIM:
To write a Python Program to integrate MYSQL with Python to search an
Employee using EMPID and delete the record of an employee if present in
already existing table EMP, if not display the appropriate message.
SOURCE CODE:
Result:
Thus, the above Python program is executed successfully and the output is
verified.
SAMPLE OUTPUT:
Python Executed Program
Output :Run-1
Output RUN – 2:
SQL OUTPUT: