0% found this document useful (0 votes)
0 views44 pages

Program

The document is a practical file for Class XII Computer Science students at PM SHRI Kendriya Vidyalaya, Greater Noida, detailing various Python programming tasks. It includes programs for arithmetic operations, Fibonacci series, file handling, and database connectivity, among others. Each program is accompanied by source code and expected outputs, serving as a comprehensive guide for students to learn and implement Python programming concepts.

Uploaded by

falcongg968
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views44 pages

Program

The document is a practical file for Class XII Computer Science students at PM SHRI Kendriya Vidyalaya, Greater Noida, detailing various Python programming tasks. It includes programs for arithmetic operations, Fibonacci series, file handling, and database connectivity, among others. Each program is accompanied by source code and expected outputs, serving as a comprehensive guide for students to learn and implement Python programming concepts.

Uploaded by

falcongg968
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 44

PM SHRI KENDRIYA VIDYALAYA

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

Write a menu driven program to define the function


4 Check (no1,no2) that takes two numbers and returns
the number that has the minimum ones digit.

Write a python Program to implement python


mathematical functions to find:
5 (i) To find Square of a number
(ii) To find Log of a number(i.e Log 10)
(iii) To find Quad of a number
6 Write a Python program to generate random number
between 1 to 6 to simulate the dice
7 Write a Python Program to Read a Text file “Story.txt”
line by line and display each word separated by ‘#’

Write a Program to read a text file “Story.txt” and


8 displays the number of Vowels/Consonants/Lowercase/
Uppercase/Characters in the file

Write a method Disp() in Python to read the lines from


9 “Poem.txt” and display those words which are less than
5 characters

Write a Python Program to read lines from a text file


10 “Sample.txt” and copy those lines into another file
which are starting with an alphabet ‘a’ or ‘A’

Write a Python Program to create a binary file with roll


11 number and name Search for a given roll number and
display the name, if not found display appropriate
messages

Write a Python Program to create a binary file with roll


12 number, name, mark and update/modify the mark for a
given roll number
13 Write a python program to create a CSV file to store
Empno,Name,Salary and Search any Empno and display
Name,Salary and if not found display appropriate
message
14 To write a Python program to implement Stack using a
list data-structure, to perform the following operations:
15 Write a Program, with separate user defined functions
to perform the following:

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"

number1 = int(input("Enter the first number: "))


number2 = int(input("Enter the second number: "))
result = check(number1, number2)
print("The number with the minimum one's digit is:", result)

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

print("The Square of a Number is:", Square(5))


print("The Log of a Number is:", Log(10))
print("The Quad of a Number is:", Quad(5, 2))

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:

print('1.Roll the Dice \n2.To exit')

user = int(input('What do you want to do: '))

if user == 1:

number = random.randint(1, 6)

print('Your Dice Number is:')


print(number)

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()

print(“Following words are of less than 5 characters”)

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()

# Function to search for a student by roll number


def Search():
f=open(“Students.dat”,’rb’)
no=int(input(“Enter Roll number of Student for Search”))
found = False
try:
while True:
S = pickle.load(f)
if S[0] == no :
print("The searched Roll. No is found and Details are:", S)
found = True
break

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

# Function to Create a student by roll number


def Create():
F = open("Marks.dat", "ab")
opt = "y"
while opt.lower() == "y":
Roll_No = int(input("Enter roll number: "))
Name = input("Enter Name: ")
Mark = int(input("Enter Marks: "))
L = [Roll_No, Name, Mark]
pickle.dump(L, F)
opt = input("Do you want to add another student detail (y/n): ")
F.close()
# Function to Update marks of a student by roll number
def Update():
F = open("Marks.dat", "rb+")
no = int(input("Enter Student Roll No to modify marks: "))
Found = 0
try:
while True:
Pos = F.tell()
S = pickle.load(F)
if S[0] == no:
print("The searched Roll No is found and Details are:", S)
S[2] = int(input("Enter New Mark to update: "))
F.seek(Pos)
pickle.dump(S, F)
Found = 1
print("Mark updated successfully and Details are:", S)
break
except EOFError:
F.close()
if Found == 0:
print("The searched Roll No is not found")

# 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()

# Function to Search student by roll number


def Search():
F = open("Emp.csv", 'r')
no = int(input("Enter Employee number to search: "))
found = 0
row = csv.reader(F)
for data in row:
if data[0] == str(no):
print("\nEmployee Details are:")
print("Name:", data[1])
print("Salary:", data[2])
found = 1
break
if found == 0:
print("Employee not found.")
F.close()
# Main Program
while True :
print("\n1. Add Employee Details")
print("2. Search Employee ")
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 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:

● To display all the information of the emp table.

Source code:-

select *from emp;

Output:-

● Display unique jobs from the EMP table.

Source code:-

SELECT DISTINCT job_name FROM EMP GROUP by job_name;


Output:-

● List the details of the emps in ascending order of the salaries.

Source code:-

SELECT *FROM EMP ORDER BY Salary ASC;

Output:-

● List the details of the employees in the ascending of the dep_id and descending of
job_name.

Source code:-

SELECT *FROM EMP ORDER BY dep_id ASC, job_name DESC;


Output:-

● Display all unique jobname in the descending order.

Source code:-

SELECT DISTINCT job_name from emp ORDER BY job_name DESC;

Output:-

● Display all the details of all managers.

Source code:-

Select *from emp where job_name=” Manager”;

Output:-
● List all the employees who joined before 1981.

Source code:-

Select *from emp where hire_date< ’1981-01-01’;

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:-

SELECT *FROM emp where job_name IN(‘analyst’,’clerk’) ORDER BY job_name DESC;

Output:-

● List the employees whose annual salary ranging from 22000 and 45000.

Source code:-

Select *from emp where salary*12 between 22000 and 45000;

Output:-
● List the employees that are having five chars and the third char must be ‘r’.

Source code:-

Select *from emp where emp_name like ‘__r___’;

Output:-

● List the employees whose emp_name has a char set ‘L’.

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:-

select *from emp where job_name not in(‘President’,’Manager’) order by salary;

Output:-
● Find the total annual salary to distribute jobwise in the year.

Source code:-

select job_name,sum(salary*12) from emp GROUP BY job_name;

Output:-

● List the employees whose salary is more than 3000 after giving 20% increment.

Source code:-

select salary+(salary*2) as increment from emp where salary+(salary*2)>3000

Output:-
PROGRAM 20
Q20. Consider the following tables Item & Customer. Write SQL Commands for the
statement
● Display all items with their details:

Source code:-

SELECT * FROM Item;

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,

(Customer.PurchaseQty * Item.Price) AS TotalCost

FROM CUSTOMER , ITEM

WHERE Customer.ItemID = Item.ItemID;

Output:-

● Insert a new customer into the Customer table:

Source code:-

INSERT INTO Customer (CustomerID, CustomerName, City, ItemID, PurchaseQty)

VALUES (105, 'Eve', 'Boston', 1, 4);

Output:-
● Find all items that are out of stock:

Source code:-

SELECT ItemName

FROM Item

WHERE StockQty = 0;

Output:-

● Update the stock quantity in the Item table after a purchase:

Source code:-

UPDATE Item SET StockQty = StockQty - (SELECT PurchaseQty FROM Customer WHERE
Customer.ItemID = Item.ItemID)

WHERE ItemID IN (SELECT ItemID FROM Customer);

Output:-

You might also like