12th Practical File For Print - 23-24
12th Practical File For Print - 23-24
Program 1 :- Write a program using function that receives two number and return
the result of all the arithmetic operations(+,-,*,/,%) .
Source Code:-
result = 0
print("**** Arithmetic operations using python function ****")
val1 = float(input("Enter the first value :"))
val2 = float(input("Enter the second value :"))
op = input("Enter any one of the operator (+,-,*,/,//,%)")
if op == "+":
res = add()
elif op == "-":
res = sub()
elif op == "*":
res = mul()
elif op == "/":
if val2 == 0:
print("Please enter a value other than 0")
else:
res = div()
1
2
elif op == "//":
res = f_div()
elif op == "%":
res = mod()
else:
print("Invalid option")
print("The result is :",res)
Output:
Source Code:-
while 1:
print("="*50)
print("***Menu driven program using python function***")
print("1 To calculate Area of circle [A=πr2]")
2
3
Output:
3
4
Source Code:-
max = 6
roll_again = "y"
while roll_again == "y" or roll_again == "Y":
print("Rolling the dice...")
val = random.randint (min, max)
print("You get... :", val)
roll_again = input("Roll the dice again? (y/n)...")
print(" Random number generator")
print(" -----------------------")
roll()
Output:
4
5
Cursor position
Program 4 :- Write a program to know the cursor position and print the text
according to the below-given specifications:
a. Print the initial position
b. Move the cursor to 4th position
c. Display next 5 characters
d. Move cursor to next 10 characters
e. Print the current cursor position
f. Print next 10 characters from current position
Source Code:-
# seek(7,0)
##0: sets the reference point at the beginning of the file
##1: sets the reference point at the current file position
##2: sets the reference point at the end of the file
5
6
Output:
Source Code:-
6
7
Output:
Program 6: Program to read and display file content line by line with each word
separated by “ # ”
Source Code:-
7
8
Output:
Program 7:- Write a program to copy all the lines that not contain the character `a' in
a file and write it to another file.
Source Code:-
8
9
print("File copied")
f1.close()
f2.close()
Output:
Program 8:- Write a program to count a total number of lines and count the total
number of lines starting with 'A', 'B', and 'C' from the file intro.txt.
Source Code:-
def starting_with():
with open("intro.txt","r") as f1:
data=f1.readlines()
cnt_lines=0
cnt_A=0
cnt_B=0
cnt_C=0
for lines in data:
cnt_lines+=1
if lines[0]=='A':
cnt_A+=1
if lines[0]=='B':
cnt_B+=1
if lines[0]=='C':
cnt_C+=1
print("""
Reading the text file to display\n""")
9
10
Output:
Program 9:- Program to create binary file to store Rollno and Name, Search any
Rollno and display name if Rollno found otherwise “Rollno not found” .
Source Code:-
10
11
student=pickle.load(f)
except EOFError:
break
ans ='y'
while ans.lower() =='y':
found = False
print("Searching a record in binary file")
print("---------------------------------")
r = int(input("Enter roll number to search:"))
for s in student:
if s[0] == r:
print("Name is :",s[1])
found = True
ans = 'n'
break
if not found:
print("Sorry,roll number not found")
ans = input("Search more(y)?:")
f.close()
Output:
11
12
Program 10:- Program to create binary file to store Rollno,Name and Marks and
update marks of entered Rollno.
Source Code:-
f = open('student.dat','rb')
student = []
while True:
try:
student=pickle.load(f)
except EOFError:
break
ans ='y'
while ans.lower() =='y':
found = False
print("Updating a record in the binary file")
print("------------------------------------")
r = int(input("Enter roll number to search:"))
for s in student:
if s[0] == r:
replace = input("Enter new name to update: ")
s[1] = replace
print("Record Updated")
print("--------------")
print("Roll Number : ", s[0])
print("Name : ", s[1])
print()
found = True
ans = 'n'
12
13
break
if not found:
print("Sorry,roll number not found\n")
ans = input("Search more(y)?:")
f.close()
Output:
Program 11:- Write a program to write data into binary file marks.dat and display
the records of students who scored more than 95 marks.
Source Code:-
13
14
print("Record:",cnt)
print("RollNO:",s[0])
print("Name:",s[1])
print("Marks:",s[2])
except Exception:
f.close()
def add_rec():
f = open("marks.dat","ab")
x = True
while x:
rn=int(input("Enter the rollno:"))
sname=input("Enter the name:")
marks=int(input("Enter the marks:"))
rec=[]
data=[rn,sname,marks]
rec.append(data)
pickle.dump(rec,f)
14
15
Output:
Program 12 :- Write a program to perform write and search operations with .csv file.
Source Code:-
ans='y'
while ans=='y':
with open('myfile.csv',mode='r') as csvfile:
myreader = csv.reader(csvfile,delimiter=',')
found=False
e = int(input("Enter Employee Number to search :"))
15
16
if not found:
print("==========================")
print(" EMPNO NOT FOUND")
print("==========================")
ans = input("Search More ? (y)")
Output:
Program 13 :- Create a CSV file by entering user-id and password, and update the
password for given user- id.
Source Code:-
16
17
fileobj = csv.writer(obj,delimiter=',')
fileobj.writerow(["User Id", "password"])
while(True):
user_id = input("enter id: ")
password = input("enter password: ")
record = [user_id, password]
fileobj.writerow(record)
x = input("press Y/y to continue and N/n to terminate the program\n")
if x in "Nn":
break
elif x in "Yy":
continue
ans ='y'
while ans:
with open("accounts.csv", "r") as obj:
file = csv.reader(obj)
print("Search and Update a record")
print("--------------------------")
search = input("Enter the user id to be searched\n")
found = "false"
for row in file:
if row[0] == search:
print("Account id found!")
update = input("Enter new password to replace: ")
row[1] = update
print("Updated password for account id ", row[0], " is ", row[1])
found = "true"
break
if found == "false":
print("Account id ", row[0], " is not found")
ans = input("Update more records ? (y)")
17
18
Output:
Stack Implementation
Source Code:-
elif ch==2:
18
19
e=pop_stack(s)
if e=="UnderFlow":
print("Stack is underflow!")
else:
print("Element popped:",e)
elif ch==3:
e=pop_stack(s)
if e=="UnderFlow":
print("Stack is underflow!")
else:
print("The element on top is:",e)
elif ch==4:
display(s)
elif ch==5:
break
else:
print("Sorry, You have entered invalid option")
def check_stack_isEmpty(stk):
if stk==[]:
return True
else:
return False
def push(stk,e):
stk.append(e)
top = len(stk)-1
def display(stk):
if check_stack_isEmpty(stk):
print("Stack is Empty")
else:
top = len(stk)-1
print(stk[top],"-Top")
for i in range(top-1,-1,-1):
print(stk[i])
def pop_stack(stk):
if check_stack_isEmpty(stk):
return "UnderFlow"
else:
e = stk.pop()
if len(stk)==0:
top = None
else:
top = len(stk)-1
return e
def peek(stk):
19
20
if check_stack_isEmpty(stk):
return "UnderFlow"
else:
top = len(stk)-1
return stk[top]
#main program begins
s=[]
main_menu()
Output:
20
21
Source Code:-
def push():
global stk
global top
empno=int(input("Enter the employee number to push:"))
ename=input("Enter the employee name to push:")
stk.append([empno,ename])
top=len(stk)-1
def display():
global stk
global top
if top==-1:
isEmpty()
else:
top=len(stk)-1
print(stk[top],"<-top")
for i in range(top-1,-1,-1):
print(stk[i])
def pop_ele():
global stk
global top
if top==-1:
isEmpty()
else:
e = stk.pop()
print("Element popped:",e)
top=top-1
def main_menu():
21
22
while True:
print("\n Stack Implementing for the employee details")
print("1. Push")
print("2. Pop")
print("3. Display")
print("4. Exit")
ch=int(input("Enter your choice:"))
print()
if ch==1:
push()
print("Element Pushed")
elif ch==2:
pop_ele()
elif ch==3:
display()
elif ch==4:
break
else:
print("Invalid Choice")
#main program begins
stk=[]
top=-1
main_menu()
22
23
Output:
23
24
Production Business
Movie_ID MovieName Type ReleaseDate
Cost Cost
Shabaash
M005 Biography 2022/02/04 1000000 800000
Mithu
24
25
Output:
[1] select * from movie;
25
26
26
27
2. Write a query to display the number 563.854741 rounding off to the next
hundred.
10. Write a query to display dayname on which movies are going to be released.
27
28
Output:
[1] select pow(5,3);
28
29
29
30
30
31
Each TeamID should have its associated name (TeamName), which should
be a string of length not less than 10 characters.
As per the preferences of the students four teams were formed as given
below. Insert these four rows in TEAM table:
3. Now create another table MATCH_DETAILS and insert data as shown below.
Choose appropriate data types and constraints for each attribute.
SecondTeam
MatchID MatchDate FirstTeamID Second FirstTeam
TeamID Score Score
M1 2021/12/20 1 2 107 93
M3 2021/12/22 1 3 86 81
M4 2021/12/23 2 4 65 67
M5 2021/12/24 1 4 52 88
M6 2021/12/25 2 3 97 68
31
32
Output:
[1] create database sports
Inserting data:
mqsql> insert into team
values(1,'Tehlka');
32
33
33
34
1. Display the matchid, teamid, teamscore whoscored more than 70 in first ining along
with team name.
34
35
35
36
36
37
37
38
Write a menu-driven program to store data into a MySQL database named shop
and table customer as following:
38
39
Add Records
Source Code:-
import mysql.connector as ms
db=ms.connect(host="localhost",user="root",password="0000")
cn=db.cursor()
cn.execute("create database if not exists shop")
cn.execute("use shop")
cn.execute("create table if not exists customer(cid int, cname varchar(20), city
varchar(20), bill_amt int, cat varchar(20))")
db.commit()
def insert_rec():
try:
while True:
cid=int(input("Enter customer id:"))
cname=input("Enter name:")
city=input("Enter city:")
bill_amt=float(input("Enter bill amount:"))
cat=input("Enter category:")
cn.execute("insert into customer
values({},'{}','{}',{},'{}')".format(cid,cname,city,bill_amt,cat))
db.commit()
print("Inserted rows successfully\n")
ch=input("Want more records? Press (N/n) to stop entry:")
if ch in 'Nn':
break
except Exception as e:
print("Error", e)
insert_rec()
39
40
Output:
Search Records
Source Code:-
import mysql.connector as ms
db=ms.connect(host="localhost",user="root",password="0000", database =
"shop")
cn=db.cursor()
cn.execute("use shop")
def search_rec():
try:
id=int(input("Enter customer id to search:"))
40
41
search_rec()
Output:
41
42
Update Records
Source Code:-
import mysql.connector as ms
db=ms.connect(host="localhost",user="root",password="0000", database =
"shop")
cn=db.cursor()
cn.execute("use shop")
def update_rec():
try:
id=int(input("Enter customer id to update:"))
query = "select * from customer where cid = {}".format(id)
cn.execute(query)
data=cn.fetchall()
for i in data:
ci=i[0]
cna=i[1]
ct=i[2]
b=i[3]
c=i[4]
if id==ci:
ch_cname=input("Want to update Name, Press 'Y':")
if ch_cname.lower()=='y':
cname=input("Enter new name:")
else:
cname=cna
ch_city=input("Want to update city, Press 'Y':")
if ch_city.lower()=='y':
city=input("Enter new city:")
else:
city=ct
ch=input("Want to update bill amount, Press 'Y':")
if ch.lower()=='y':
bill_amt=float(input("Enter new bill amount:"))
else:
42
43
bill_amt=b
ch_cat=input("Want to update Category, Press 'Y':")
if ch_cat.lower()=='y':
cat=input("Enter new category:")
else:
cat=c
cn.execute("update customer set cname='{}', city='{}',
bill_amt={},cat='{}'where cid={}".format(cname,city,bill_amt,cat,id))
db.commit()
print("Updated successfully\n")
break
else:
print("Record Not Found...\n")
except Exception as e:
print("Error",e)
update_rec()
Output:
43
44
Display Records
Source Code:-
import mysql.connector as ms
db=ms.connect(host="localhost",user="root",password="0000", database =
"shop")
cn=db.cursor()
cn.execute("use shop")
def view_rec():
try:
cn.execute("select * from customer")
data=cn.fetchall()
cnt=0
for i in data:
cnt=cnt+1
print("Record:",cnt)
print('*'*25)
print("Customer ID:",i[0])
print("Customer Name:",i[1])
print("City:",i[2])
print("Bill Amount:",i[3])
print("Category:",i[4])
print('*'*25)
except Exception as e:
print("Error",e)
view_rec()
44
45
Output:
Delete Records
Source Code:-
import mysql.connector as ms
db=ms.connect(host="localhost",user="root",password="0000", database =
"shop")
cn=db.cursor()
cn.execute("use shop")
45
46
def delete_rec():
try:
delete_rec()
Output:
46
47
Alter Table
Source Code:-
import mysql.connector as ms
db=ms.connect(host="localhost",user="root",password="0000", database =
"shop")
cn=db.cursor()
cn.execute("use shop")
def alter_table():
try:
col_name=input("Enter column name to add: ")
col_type=input("Enter column data type: ")
query = "alter table customer add " + col_name +" "+ col_type
cn.execute(query)
db.commit()
print("\nAlterted table successfully")
print("New Column added\n")
except Exception as e:
print("Error",e)
alter_table()
Output:
47
48
48
49
49
50
50