Program
Program
GREATER NOIDA
Computer Science (083)
Class XII
Practical File
Rajeshwar Singh
Roll No: 38
INDEX
S no. Program Date Sign
1 Write a menu driven Python Program to perform
Arithmetic operations(+,-,*,/) based on user's choice
2 Write a Python Program to display Fibonacci Series up
to 'n' numbers
3 Write a menu driven Python Program to find Factorial
using function
Python-MySQL Connectivity
To write a Python Program to integrate MYSQL with
16 Python to create a Database and Table to store the
details of Students.
17 Write a Program for Updating Records in a Table
Studentinfo created earlier.
18 Write a Program for Deleting records in a table
Studentinfo created earlier
SQL Queries
19 Queries based on Table EMPLOYEE
20 Consider the following tables Item & Customer. Write
SQL Commands for the statement
Program 1
Q1. Create a menu driven Python program to perform Arithmetic operations.
Source code:-
print('1. Addition')
print('2. Subtraction')
print('3. Multiplication')
print('4. Division')
opt=int(input("Enter Your Choice: "))
x = int(input('Enter the first number:'))
y = int(input('Enter the second number:'))
if opt == 1:
print('The result of addition:',(x+y))
elif opt == 2:
print('The result of subtraction:',(x-y))
elif opt == 3:
print('The result of multiplication:',(x*y))
elif opt == 4:
if y==0:
print('Invalid command')
else:
print('The result of division:',(x/y))
else:
print('Invalid Choice')
Output:-
Program 2
Q2. Display Fibonacci Series up to ‘n’ numbers.
Source code:-
nterms = int(input('How many Fibonacci no. you want to display?'))
first,second = 0,1
if nterms <=0 :
print('Please enter a positive integer')
else:
print(first)
print(second)
for i in range(2,nterms):
third=first+second
first=second
second=third
print(third)
Output:-
Program 3
Q3. Write a menu driven Python Program to find Factorial and sum of list of numbers
using function.
Source code:-
def factorial(no):
f=1
if no<0:
print('Sorry, we cannot take factorial for negative no. ')
elif no==0:
print('The factorial of 0 is 1 ')
else:
for i in range(1,no+1):
f=f*i
print('Factorial of ',no, 'is',f)
print('1.To find factorial')
print('Enter choice:')
opt=int(input("Enter Your Choice: "))
if opt==1:
n=int(input('Enter a no. to find factorial:'))
factorial(n)
Output:-
Program 4
Q4. Write a Python Program to define a function check(no1,no2) that takes two
numbers and returns the number which has the minimum ones digit.
Source code:-
def check(no1, no2):
if (no1%10)<(no2%10):
return no1
elif (no1%10)>(no2%10):
return no2
else:
return "Both numbers have the same one's digit"
Output:-
Program 5
Q5. Write a Python program to implement python mathematical functions to find:
i) Square of a number
ii) Log of a number (i.e 10)
iii) Quad of a number
Source code:-
import math
def Square(num):
S = math.pow(num, 2)
return S
def Log(num):
S = math.log10(num)
return S
def Quad(X, Y):
S = math.sqrt(X**2 + Y**2)
return S
Output:-
Program 6
Q6. Python program that generates a random number between 1 to 6 to stimulate a
dice roll.
Source code:-
import random
while True:
if user == 1:
number = random.randint(1, 6)
else:
break
Output:-
Program 7
Q7.Write a Python Program to Read a text file “Story
txt” line by line and display each word separated by ‘#’
Source Code-:
f=open(“story.txt",'r')
content=f.readlines()
print(content)
for i in content:
words=i.split()
for a in words:
print(a+"#",end="")
f.close()
Output:-
Project 8
Q8. Write a Program to read a text file “Story.txt” and display the number of Vowels/
Consonants/ Lowercase/ Uppercase/Characters in the file.
Source Code-:
f=open(“story.txt",'r')
content=f.read()
Vowels=0
Consonants=0
Lowercase=0
Uppercase=0
for ch in content:
if ch in “aeiou”:
Vowels = Vowels+1
elif ch in “bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ”:
Consonants = Consonants +1
elif ch.islower() :
Lowercase = Lowercase + 1
elif ch.isupper() :
Uppercase = Uppercase + 1
f.close()
print(“Total number of Vowels are ”,Vowels)
print(“Total number of Consonants are ”,Consonants)
print(“Total number of Lowercase characters are ”,Lowercase)
print(“Total number of Uppercase characters are ”,Uppercase )
Output:-
Program 9
Q9. To write a method Disp ( ) in Python, to read the lines from Poem.txt and display
those words which are less than 5 characters.
Source Code-:
def Disp(file_name):
f=open(“file_name”,’r’)
content=f.read()
w=content.split()
for i in w:
if len(i)<5:
print(i,end=””)
print()
f.close()
Disp(“Poem.txt”)
Output:-
Program 10
Q10. To write a python program to read lines from a text file “Story.txt” and copy
those lines into another file which are starting with an alphabet ‘a’ or ‘A’.
Source Code-:
F1=open("Story.txt",'r')
F2=open("Newfile.txt",'w')
S=F1.readlines()
for i in S:
if i[0]=='A' or i[0]=='a':
F2.write(i)
print("Written Successfully")
F2=open("Newfile.txt",'r')
str=F2.read()
print(str)
F1.close()
F2.close()
Output:-
Program 11
Q11. 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
# Function to Create a student by roll number
def Create():
f=open("Students.dat", 'ab')
opt=’y’
while opt.lower() ==’y’:
Roll_no=int(input(“Enter Roll Number: ”))
Name=input(“Enter Name: ”)
L=[Roll_no,Name]
pickle.dump(L,F)
opt=input(“Do you want to add another student detail (y/n): ”)
f.close()
except :
f.close()
if found==False :
print("The Searched Roll. No is not found.")
# Main Program
while True :
print("\n1. Add Student Details")
print("2. Search Student")
print("3. Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
Create()
elif choice == 2:
Search()
elif choice == 3:
print(“Exiting…”)
break
else:
print("Invalid choice! Please try again.")
Output:-
Program 12
Q.12 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
# Main Program
while True:
print("\n1. Add Student Details")
print("2. Update Marks")
print("3. Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
Create()
elif choice == 2:
Update()
elif choice == 3:
print("Exiting…")
break
else:
print("Invalid choice! Please try again.")
Output:-
Program 13
Q.13 To write a Python program Create a CSV file to store Emp.no, Name, Salary and
search any Emp.no and display , Name, Salary and if not found display appropriate
message.
Source code:-
import csv
# Function to Create a student by roll number
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()
Program 14
Q14. To write a Python program to implement Stack using a list data-structure, to
perform the following operations:
(i)To Push an object containing Doc_ID and Doc_name of doctors who specialize in
"ENT" to the stack.
(ii) To Pop the objects from the stack and display them.
(iii) To display the elements of the stack (after performing PUSH or POP)
Source code:-
def Push():
Doc_ID=int(input("Enter the Doctor ID:"))
Doc_Name=input("Enter the Name of the Doctor:")
Mob=int(input("Enter the Mobile Number of the Doctor:"))
Special=input("Enter the Specialization:")
if Special=='ENT':
Stack.append([Doc_ID,Doc_Name])
def Pop():
if Stack==[]:
print("Stack is empty")
else:
print("The deleted doctor detail is:",Stack.pop())
def Peek():
if Stack==[]:
print("Stack is empty")
else:
top=len(Stack)-1
print("The top of the stack is:",Stack[top])
def Disp():
if Stack==[]:
print("Stack is empty")
else:
top=len(Stack)-1
for i in range(top,-1,-1):
print(Stack[i])
Stack=[]
ch='y'
print("Performing Stack Operations Using List\n")
while ch=='y' or ch=='Y':
print()
print("1.PUSH")
print("2.POP")
print("3 PEEK")
print("4.Disp")
opt=int(input("Enter your choice:"))
if opt==1:
Push()
elif opt==2:
Pop()
elif opt==3:
Peek()
elif opt==4:
Disp()
else:
print("Invalid Choice, Try Again!!!")
ch=input("\nDo you want to Perform another operation(y/n):")
if ch=='n':
exit()
Output:-
Program 15
Q15.Write a Program, with separate user defined functions to perform the following:
● To create a function Push(Stk,D) Where Stack is an empty list and D is a
Dictionary of items. From this dictionary Push the keys into a stack,where the
corresponding value is greater than 70
Source code:-
def Push(Stk,D):
for i in D:
if D[i]>70:
Stk.append(i)
● To create a Function Pop(Stk), where Stk is a Stack implemented by a list of
Student names. The function returns the items deleted from the stack.
Source code:-
def Pop(Stk):
if Stk==[]:
print( “Stack is Empty”)
else :
print(“The deleted element is:”,end=’’)
return Stk.pop()
● To display the elements of the stack(after performing Push or Pop)
Source code:-
def Display():
if Stk==[]
return”Stack is Empty”
else:
top=len(Stk)-1
for i in range (top,-1,-1):
print(Stk[i])
Program 16
Q16.To write a Python Program to integrate MYSQL with Python to create a Database
and Table to store the details of Students.
Source code:-
# Connecting to the database server
import mysql.connector
con = mysql.connector.connect(host=”localhost”,user=”root”,passwd=”root”)
mycursor = con.cursor()
mycursor.execute(“Create Database Student”)
mycursor.execute(“Use Student”)
#Creating the Table
mycursor.execute(“Create Table studentinfo (name Varchar(30), age int(3), gender Char(1) )”)
#Inserting data into table
sql = “Insert into studentinfo Values(“Ashok”,17,”M”)”
mycursor.execute(sql)
#Reading from database table
sql1=”Select * from studentinfo”
mycursor.execute(sql1)
result=mycursor.fetchall()
for row in result:
name=row[0]
age=row[1]
gender=row[2]
print(“Name=%s,Age=%d,Gender=%c”%(name,age,gender))
# Closing Database Server
con.close()
Output:-
Program 17
Q17.Write a Program for Updating Records in a Table Studentinfo created earlier.
Source code:-
# Connecting to the database server
import mysql.connector
con = mysql.connector.connect(host=”localhost”,user=”root”,passwd=”root”)
mycursor = con.cursor()
mycursor.execute(“Use Student”)
#Updating Records in a Table
sql=”Update studentinfo Set age=age-3 where age=21”
mycusor.execute(sql)
con.commit()
#Reading from database table
sql1=”Select * from studentinfo”
mycursor.execute(sql1)
result=mycursor.fetchall()
for row in result:
name=row[0]
age=row[1]
gender=row[2]
print(“Name=%s,Age=%d,Gender=%c”%(name,age,gender))
Output:-
PROGRAM 18
Q18. Delete records in a Table student created earlier
Source code:-
# Connecting to the database server
import mysql.connector
con = mysql.connector.connect(host="localhost", user="root", passwd="India@1234",
database="tuition")
mycursor = con.cursor()
#Deleting Records in a Table
sql = "DELETE FROM student WHERE name='vishal' "
mycursor.execute(sql)
#Reading from database table
sql1 = "SELECT * FROM student"
mycursor.execute(sql1)
result = mycursor.fetchall()
print(result)
# Closing Database Server
con.close()
Output:-
PROGRAM 19
Q19. QUERIES based on the EMP table given below.
QUERIES:
Source code:-
Output:-
Source code:-
Source code:-
Output:-
● List the details of the employees in the ascending of the dep_id and descending of
job_name.
Source code:-
Source code:-
Output:-
Source code:-
Output:-
● List all the employees who joined before 1981.
Source code:-
Output:-
● List the emp_id, emp_name, sal and daily salary of all employees in the ASC order of
Annual salary.
Source code:-
SELECT emp_id, emp_name, salary/30 AS daily_salary FROM emp ORDER BY Salary*12 DESC;
Output:-
● List all the employees who are either ‘CLERK’ or ‘ANALYST’ in the desc order.
Source code:-
Output:-
● List the employees whose annual salary ranging from 22000 and 45000.
Source code:-
Output:-
● List the employees that are having five chars and the third char must be ‘r’.
Source code:-
Output:-
Source code:-
Select *from emp where emp_name like ‘%L%’;
Output:-
● List all the employees except ‘President’ and ‘Manager’ in ASC order of salaries.
Source code:-
Output:-
● Find the total annual salary to distribute jobwise in the year.
Source code:-
Output:-
● List the employees whose salary is more than 3000 after giving 20% increment.
Source code:-
Output:-
PROGRAM 20
Q20. Consider the following tables Item & Customer. Write SQL Commands for the
statement
● Display all items with their details:
Source code:-
Output:-
● Join Item and Customer to get details of customers along with the items they
purchased
Source code:-
SELECT
Customer.CustomerID,
Customer.CustomerName,
Customer.City,
Item.ItemName,
Customer.PurchaseQty,
Item.Price,
Output:-
Source code:-
Output:-
● Find all items that are out of stock:
Source code:-
SELECT ItemName
FROM Item
WHERE StockQty = 0;
Output:-
Source code:-
UPDATE Item SET StockQty = StockQty - (SELECT PurchaseQty FROM Customer WHERE
Customer.ItemID = Item.ItemID)
Output:-