G12 - Computer Science - Lab Programs 1 To 20
G12 - Computer Science - Lab Programs 1 To 20
Source Code:
def Add(a,b):
print(a+b)
def Sub(a,b):
print(a-b)
def Div(a,b):
print(a/b)
def Mul(a,b):
print(a*b)
Num_1 = int(input("Enter no.1:"))
Num_2 = int(input("Enter no.2:"))
print("Type 1: Addition")
print("Type 2: Subtraction")
print("Type 3: Division")
print("Type 4: Multiplication")
ch=int(input("Enter your Choice 1,2,3,4:"))
if ch==1:
Add(Num_1, Num_2)
elif ch==2:
Sub(Num_1, Num_2)
elif ch==3:
Div(Num_1, Num_2)
elif ch==4:
Mul(Num_1, Num_2)
else:
print("Wrong Input Choice")
Program No: 02
Aim: To write a program in python to generate random number between 1 and 6 (stimulation a dice)
Source Code:
import random
print("To roll the dice, hit enter...!!!")
a=input()
print(random.randint(1,6))
Program No: 03
Aim: To write a program in python to read a text file line by line and print it
Source Code:
file=open('Forest.txt','r')
a=file.readlines()
for i in a:
print(i)
Note: Forest.txt file should contain at least 5 to 6 lines
Program No: 04
Program Name: Moving Lines from a Text File To Another Which Has 'A'
Aim: To write a python program to move all the lines that contains the character 'a' in a text
file(old_text.txt)
Source Code:
A=open("C:\\Users\\HP\\AppData\\Local\\Programs\\Python\\Python38-32\\old_text.txt","r")
B=open("C:\\Users\\HP\\AppData\\Local\\Programs\\Python\\Python38-32\\new_text.txt","w")
lines=A.readlines()
for i in lines:
if 'a' in i or 'A' in i:
B.write(i)
print("Copying or Moving lines which has 'a' in it Completed Successfully")
A. close()
B. close()
Program No: 05
Program Name: Read and Display words in the Text File separated by ‘#’
Aim: To write a program in python to read a text file line by line and display each word separated by a
‘#’
Source Code:
file=open('Forest.txt','r')
for i in file:
for word in i.split():
print(word, end=" # ")
Program No: 06
Aim: To write a python program to read the text files line by line and to find the number of vowels,
consonants, lower and upper case characters
Source Code:
A=open("C:\\Users\\HP\\AppData\\Local\\Programs\\Python\\Python38-32\\old_text.txt","r")
x=A.read()
print(x)
vow=0
cons=0
small=0
capital=0
for ch in x:
if(ch.islower()):
small=small+1
elif(ch.isupper()):
capital=capital+1
ch=ch.lower()
vow=vow+1
cons=cons+1
Program No: 07
Aim: To write a Python program to create a binary file with the name and roll number. Search for a
given roll number and display the name, if not found, display an appropriate message.
Source Code:
import pickle
def BinaryWrite():
Records = []
while True:
Records.append(record)
pickle.dump(Records, File)
File.close()
def BinarySearch():
Records = pickle.load(File)
match = False
if record[0] == roll_num:
print("Record matched!")
print(record)
match = True
break
if match == False:
File.close()
BinaryWrite()
BinarySearch()
Program No: 08
Aim: To write a Python program to create a binary file with roll number, name and marks. Input a roll
number and update the marks.
Source Code:
import pickle
def Bwrite():
f=open("Binfile.dat","wb")
sturec=[]
while True:
sturec=[rno,name,mark]
pickle.dump(sturec,f)
if ch== "N":
break
f.close()
def Bupdate():
f=open("Binfile.dat","rb+")
found=False
try:
while True:
rpos=f.tell()
stu=pickle.load(f)
if stu[0]==rno:
f.seek(rpos)
pickle.dump(stu,f)
found=True
except EOFError:
if found==False:
else:
f.close()
def BRead():
f=open("Binfile.dat",'rb')
try:
while True:
rec=pickle.load(f)
for i in rec:
print(i)
except Exception:
f.close()
Bwrite()
Bupdate()
BRead()
Program No: 09
Aim: To write a Python program to append student records [roll number, name, mark] to a binary file,
by getting data from the user.
Source Code:
import pickle
def BinaryAppend():
Records = []
while True:
Records.append(record)
break
pickle.dump(Records, File)
File.close()
def BinaryRead():
try:
while True:
rec=pickle.load(File)
for i in rec:
print(i)
except Exception:
File.close()
BinaryAppend()
#BinaryAppend()
BinaryRead()
Program No: 10
Aim: To create a CSV file by entering the user-id and password, read and search the password for the
given user-id.
Source Code:
import csv
def CSVWrite():
Records = []
while True:
Records.append([userID, password])
if choice in "NOno":
break
Writer =csv.writer(File)
Writer.writerow(("UserID","Password"))
Writer.writerows(Records)
File.close()
def CSVRead():
Records =csv.reader(File)
for details in Records:
print(details)
File.close()
def CSVSearch():
flag=0
new=csv.reader(File)
for i in new:
if i[0]==search:
flag=1
break
if flag==0:
File.close()
CSVWrite()
CSVRead()
CSVSearch()
Program No: 11
Aim: To write a Python program to read a CSV file having a tab delimiter.
Source Code:
import csv
def CSVWrite():
Records = []
while True:
Records.append([userID, password])
if choice in "NOno":
break
Writer =csv.writer(File,delimiter='\t')
Writer.writerow(("UserID","Password"))
Writer.writerows(Records)
File.close()
def CSVRead():
print(details)
CSVWrite()
CSVRead()
Program No: 12
Aim: To write a Python program that generates 4 terms of an AP by providing initial and steps values to
a function that returns the first four terms of the series.
Source Code:
def Arithemetic_Progression( start = 0, terms = 0, step = 1 ):
Progression = []
Progression.append(start + (term-1)*step)
return Progression
print(Arithemetic_Progression(start,terms,step))
Program No: 13
Aim: To write a Python program to implement a stack using a list data structure. (push, pop and peek)
Source Code:
def IsEmpty(stack): # Checks if the given stack is empty or not:
if stack == []:
return True
else:
return False
stack.append(item);TOP = len(stack) - 1
if IsEmpty(stack):
return "Underflow"
else:
item = stack.pop()
if len(stack) == 0:
TOP = None
else:
TOP = len(stack) - 1
return item
if IsEmpty(stack):
return "Underflow"
else:
TOP = len(stack) - 1
return stack[TOP]
def Display(stack):
if IsEmpty(stack):
else:
print("\t",stack[value])
stack = Stack
TOP = None
leave = False
choice = 0
print("X===={STACK:OPERTATIONS}====X")
print("X X")
print("X 1. Push X")
print("X========----------========X\n")
print("\nX========----------========X\n")
if choice == 1:
print("\nX========----------========X\n")
Push(stack, item)
elif choice == 2:
item = Pop(stack)
if item == "Underflow":
print("\nX========----------========X\n")
else:
print("\nX========----------========X\n")
elif choice == 3:
item = Peek(stack)
if item == "Underflow":
print("\nX========----------========X\n")
else:
nX========--------------------========X\n")
elif choice == 4:
Display(stack)
print("\nX========----------========X\n")
elif choice == 5:
leave = True
else:
print("\nX========----------========X\n")
return stack
StackGUI()
Program No: 14
Aim: To write a Python program to create a dictionary containing names and marks as key value pairs of
5 students. Define two user defined functions to perform the following operations:
i) Push the keys (name of the student) of the dictionary into a stack, where the corresponding value
(marks) is greater than 75.
Source Code:
def DictPush(stack,name):
stack.append(name)
def DictPop(stack):
if stack!=[]:
return stack.pop()
else:
return None
stu_dict={}
for i in range(5):
stu_dict[keys]=value
print(stu_dict)
stack=[]
for i in stu_dict:
if stu_dict[i]>=75:
DictPush(stack,i)
while True:
if stack!=[]:
print(DictPop(stack),end=" ")
else:
break
Program No: 15
Aim: Write a Python program with user defined functions to perform the following operations based on
the list.
Source Code:
import random
def LISTPUSH(stack,element):
stack.append(element)
def LISTPOP(stack):
return stack.pop()
List1=[]
for i in range(11):
List1.append(random.randint(1,100))
print(List1)
stack=[]
for i in List1:
if i%2==0:
LISTPUSH(stack,i)
while True:
if stack!=[]:
print(LISTPOP(stack),end=" ")
else:
break
Program No: 16
Aim: To Integrate SQL with Python by importing suitable module and display the successful connection
established message.
Source Code:
import mysql.connector as sql
mycon=sql.connect(host='localhost',user='root',passwd='root',database='xii_22_23')
if mycon.is_connected():
Program No: 17
Program Name: Interfacing SQL with Python – Retrieval of records using fetchone() method
Aim:
To Integrate SQL with Python by importing suitable module and display the records from the table
PLAYER using fetchone().
Source Code:
import mysql.connector as sql
mycon=sql.connect(host='localhost',user='root',passwd='root',database='xii_22_23')
if mycon.is_connected():
mycur=mycon.cursor()
data=mycur.fetchone()
print(row,end=" ")
Program No: 18
Program Name: Interfacing SQL with Python – Retrieval of records using fetchall() method
Aim:
To Integrate SQL with Python by importing suitable module and display the records from the table
PLAYER using fetchall().
Source Code:
import mysql.connector as sql
mycon=sql.connect(host='localhost',user='root',passwd='root',database='xii_22_23')
if mycon.is_connected():
mycur=mycon.cursor()
data=mycur.fetchall()
print(row)
Program No: 19
Program Name: Interfacing SQL with Python – Deletion of record from the table
Aim:
Integrate SQL with python by importing the suitable module, input player code, and delete the record
from the table PLAYER.
Source Code:
import mysql.connector as sql
mycon=sql.connect(host='localhost',user='root',passwd='root',database='xii_22_23')
if mycon.is_connected():
mycur=mycon.cursor()
data=mycur.execute(sql)
mycon.commit()
print(mycur.fetchall())
Program No: 20
Aim: To write SQL commands create and insert the data into the table STUDENT and to execute the
query for the problem statement given.
SQL Command:
i) To display the records from table student in alphabetical order as per the name of the student.
SELECT * FROM STUDENT ORDER BY NAME;
ii) To display Class and total number of students who have secured more than 450 marks, class
wise.
SELECT CLASS,COUNT(*) FROM STUDENT WHERE MARKS>450 GROUP BY CLASS ;
iii) To increase marks of all students by 20 whose class is “XII”.
UPDATE STUDENT SET MARKS=MARKS+20 WHERE CLASS="XII";
iv) To display the count and city where number of city is more than 1.
SELECT COUNT(*),CITY FROM STUDENT GROUP BY CITY HAVING COUNT(*)>1;
v) To display maximum and minimum DOB of female students.
SELECT MAX(DOB),MIN(DOB) FROM STUDENT WHERE GENDER='F';
TABLE to be drawn on the left side of the record notebook.
Table : STUDENT