Program No: 01
Program Name: Simple Calculator in Python
Aim: To Create a Simple Calculator in Python
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
Program Name: Random Number Generator
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([Link](1,6))
Program No: 03
Program Name: Reading a Text File (line by line)
Aim: To write a program in python to read a text file line by line and print it
Source Code:
file=open('[Link]','r')
a=[Link]()
for i in a:
print(i)
Note: [Link] 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=[Link]()
for i in lines:
if 'a' in i or 'A' in i:
[Link](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('[Link]','r')
for i in file:
for word in [Link]():
print(word, end=" # ")
Program No: 06
Program Name: Display the number of Vowels/Consonants/Lowercase/Uppercase Characters in a
Text File
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=[Link]()
print(x)
vow=0
cons=0
small=0
capital=0
for ch in x:
if([Link]()):
small=small+1
elif([Link]()):
capital=capital+1
ch=[Link]()
if(ch in ['a', 'e', 'i', 'o', 'u']):
vow=vow+1
elif (ch in ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z']):
cons=cons+1
print("Number of Vowels: ",vow)
print("Number of Consonanats: ",cons)
print("Number of Lower case characters: ",small)
print("Number of Upper case characters: ",capital)
Program No: 07
Program Name: Searching in a binary file
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 = []
with open('[Link]', "wb") as File:
while True:
roll_num = int(input("Enter the Roll Number:
")) name = input("Enter the Name: ")
record = [roll_num, name]
[Link](record)
choice = input("Do you want to continue? y/n: ")
if choice in "NOno" and choice != "":
break
[Link](Records, File)
print("Record Written Successfully!")
[Link]()
def BinarySearch():
with open('[Link]', "rb") as File:
Records = [Link](File)
roll_num = int(input("Enter the Roll Number to be searched: "))
match = False
for record in Records:
if record[0] == roll_num:
print("Record matched!")
print(record)
match = True
break
if match == False:
print("Record not found ... ")
[Link]()
BinaryWrite()
BinarySearch()
Program No: 08
Program Name: Updating record in a binary file
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("[Link]","wb")
sturec=[]
while True:
rno=int(input("Enter the roll no"))
name=input("Enter the name")
mark=float(input("Enter aggregate mark"))
sturec=[rno,name,mark]
[Link](sturec,f)
ch=input("Do you want to continue : Y/N ")
if ch== "N":
break
[Link]()
def Bupdate():
f=open("[Link]","rb+")
found=False
rno=int(input("Enter the rollno to be searched"))
mark=float(input("Enter aggregate marks to be updated"))
try:
while True:
rpos=[Link]()
stu=[Link](f)
if stu[0]==rno:
print("Record Found... Updating...")
stu[2]=mark
[Link](rpos)
[Link](stu,f)
found=True
except EOFError:
if found==False:
print("Sorry,No matching record found")
else:
print("Record successfully updated.")
[Link]()
def BRead():
f=open("[Link]",'rb')
try:
while True:
rec=[Link](f)
for i in rec:
print(i)
except Exception:
[Link]()
Bwrite()
print("Data has been written successfully")
Bupdate()
BRead()
Program No: 09
Program Name: Appending record into a binary file
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 = []
with open("[Link]", "ab") as File:
while True:
roll_num = int(input("Enter the Roll Number:
")) name = input("Enter the Name: ")
marks = int(input("Enter the Marks: "))
record = [roll_num, name, marks]
[Link](record)
choice = input("Do you want to continue? y/n: ")
if choice in "NOno" and choice != "":
break
[Link](Records, File)
print("Record Appended Successfully!")
[Link]()
def BinaryRead():
try:
with open("[Link]","rb") as File:
while True:
rec=[Link](File)
for i in rec:
print(i)
except Exception:
[Link]()
BinaryAppend()
#BinaryAppend()
BinaryRead()
Program No: 10
Program Name: Searching in a CSV file
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:
userID = int(input("Enter UserID: "))
password = input("Enter Password: ")
[Link]([userID, password])
choice = input("Do you want to continue? y/n: ")
if choice in "NOno":
break
with open("[Link]", "w", newline = '') as File:
Writer =[Link](File)
[Link](("UserID","Password"))
[Link](Records)
[Link]()
def CSVRead():
with open("[Link]","r") as File:
Records =[Link](File)
for details in Records:
print(details)
[Link]()
def CSVSearch():
flag=0
search=input("Enter the UserID for the password:")
with open("[Link]","r") as File:
new=[Link](File)
for i in new:
if i[0]==search:
print("THe password is:",i[1])
flag=1
break
if flag==0:
print("Record not found")
[Link]()
CSVWrite()
CSVRead()
CSVSearch()
Program No: 11
Program Name: Reading CSV file – tab delimiter
Aim: To write a Python program to read a CSV file having a tab delimiter.
Source Code:
import csv
def CSVWrite():
Records = []
while True:
userID = int(input("Enter UserID: "))
password = input("Enter Password: ")
[Link]([userID, password])
choice = input("Do you want to continue? y/n: ")
if choice in "NOno":
break
with open("[Link]", "w", newline = '') as File:
Writer =[Link](File,delimiter='\t')
[Link](("UserID","Password"))
[Link](Records)
[Link]()
def CSVRead():
with open("[Link]","r") as File:
Records = [Link](File, delimiter='\t')
for details in Records:
print(details)
CSVWrite()
CSVRead()
Program No: 12
Program Name: Arithmetic Progression using functions
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 = []
for term in range( 1, terms + 1 ):
[Link](start + (term-1)*step)
return Progression
start = int(input("Enter the Starting Value: "))
terms = int(input("Enter the Total Number of Terms: "))
step = int(input("Enter the Step value: "))
print(Arithemetic_Progression(start,terms,step))
Program No: 13
Program Name: Stack Implementation using Lists
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
def Push(stack, item): # Appends a given value on top of the stack:
[Link](item);TOP = len(stack) - 1
def Pop(stack): # Removes the topmost value in a given stack:
if IsEmpty(stack):
return "Underflow"
else:
item = [Link]()
if len(stack) == 0:
TOP = None
else:
TOP = len(stack) - 1
return item
def Peek(stack): # Displays the topmost value in a given stack:
if IsEmpty(stack):
return "Underflow"
else:
TOP = len(stack) - 1
return stack[TOP]
def Display(stack):
if IsEmpty(stack):
print("Given Stack is Empty.")
else:
TOP = len(stack) - 1 print("\
t",stack[TOP], "<-= Top") for
value in range(TOP - 1, -1, -1):
print("\t",stack[value])
def StackGUI(Stack = []):
stack = Stack
TOP = None
leave = False
choice = 0
while leave != True:
print("X===={STACK:OPERTATIONS}====X")
print("X X")
print("X 1. Push X")
print("X 2. Pop X")
print("X 3. Peek X")
print("X 4. Display X")
print("X 5. Exit X")
print("X X")
print("X========----------========X\n")
choice = int(input(" Enter your choice: "))
print("\nX========----------========X\n")
if choice == 1:
item = int(input("Enter item (integer): "))
print("\nX========----------========X\n")
Push(stack, item)
elif choice == 2:
item = Pop(stack)
if item == "Underflow":
print("Stack Underflow! The Stack is Empty:")
print("\nX========----------========X\n")
else:
print("Item has been popped:",item)
print("\nX========----------========X\n")
elif choice == 3:
item = Peek(stack)
if item == "Underflow":
print("Stack Underflow! The Stack is Empty:")
print("\nX========----------========X\n")
else:
print("Topmost Item:",item) print("\
nX========--------------------========X\n")
elif choice == 4:
Display(stack)
print("\nX========----------========X\n")
elif choice == 5:
leave = True
else:
print("Choice is Invalid: Try again!")
print("\nX========----------========X\n")
return stack
StackGUI()
Program No: 14
Program Name: Push and pop operations in Dictionary using functions
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.
ii) Pop and display the content of the stack.
Source Code:
def DictPush(stack,name):
[Link](name)
def DictPop(stack):
if stack!=[]:
return [Link]()
else:
return None
stu_dict={}
for i in range(5):
keys=input("Enter the Student Name:")
value=int(input("Enter the Mark:"))
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
Program Name: Push and pop operations in Lists using functions
Aim: Write a Python program with user defined functions to perform the following operations based on
the list.
A list is having 10 integers.
i) To push the even numbers from the list into a stack.
ii) Pop and display the content of the stack.
Source Code:
import random
def LISTPUSH(stack,element):
[Link](element)
def LISTPOP(stack):
return [Link]()
List1=[]
for i in range(11):
[Link]([Link](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
Program Name: Interfacing SQL with Python – Connection Establishment
Aim: To Integrate SQL with Python by importing suitable module and display the successful connection
established message.
Source Code:
import [Link] as sql
mycon=[Link](host='localhost',user='root',passwd='root',database='xii_22_23')
if mycon.is_connected():
print("Connection has been established successfully")
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 [Link] as sql
mycon=[Link](host='localhost',user='root',passwd='root',database='xii_22_23')
if mycon.is_connected():
print("Connection has been established successfully")
mycur=[Link]()
[Link]("select * from player")
data=[Link]()
for row in data:
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 [Link] as sql
mycon=[Link](host='localhost',user='root',passwd='root',database='xii_22_23')
if mycon.is_connected():
print("Connection has been established successfully")
mycur=[Link]()
[Link]("select * from student")
data=[Link]()
for row in data:
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 [Link] as sql
mycon=[Link](host='localhost',user='root',passwd='root',database='xii_22_23')
if mycon.is_connected():
print("Connection has been established successfully")
mycur=[Link]()
a=int(input("Enter the Player Code to delete"))
sql="delete from student where rollno='%d'"%(a)
data=[Link](sql)
[Link]()
[Link]("select * from student")
print([Link]())
Program No: 20
Program Name: SQL Commands
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