COMPUTER SCIENCE Class 12 Practical (Up)
COMPUTER SCIENCE Class 12 Practical (Up)
Lab file
Session-2024-25
A)Create the table B) Insert the records C) Display the records using fetchall function
44. Write a program to connect python with mysql using database connectivity and perform the
Sollowing operations in database
a) Count the number of records in each stream and display it b) Display the number of
madents who have secured 'A'Grade c) Add a new column called Rank in the table.
45. Write a program to connect python with mysql using database connectivity and perform the
following operations in database
aiDisplay all the records of students in the ascending order of Name of the student b)
Display the number of records whose name starts with D e) Delete the record whose ID is 3
Program-1
1) Write a program to reverse of three numbers
a=int (input ('enter a three-digit number'))
x=a//100
b=a%100
y=b//10
z=b%10
print("Reversed number:",z*100+y*10+x)
OUTPUT
Program-2
2) Write a program to classify odd and even numbers.
a=int(input('enter a number:'))
if a%2==0:
print('Even')
else:
print("odd")
OUTPUT
Program-3
3) Write a program to take out largest number from 3 numbers.
a=int(input('enter a number:'))
b=int(input('enter a number:'))
c=int(input('enter a number:'))
if a>b and a>c:
print(a,'is the greatest number.')
elif b>c and b>a:
print(b,'is the greatest number.')
else:
print(c,'is the greatest number.')
OUTPUT
Program-4
Write a program to classify uppercase/ lowercase/ digit/ special character
a=input('Enter a character:')
if a>='A' and a<='Z':
print('Uppercase')
elif a>='a' and a<='z':
print('Lowercase')
elif a>='0' and a<='9':
print('Digit')
else:
print('Special character:')
OUTPUT
Program-5
Write a program to take out natural numbers up to n
n=int(input('Enter a number:'))
for i in range(1, n+1):
print(i)
OUTPUT
Program-6
Write a program to take out sum of natural numbers till n
n=int(input('Enter a number:'))
sum=0
for i in range (1, n+1):
sum+=i
print(sum)
output
Program-7
Write a program to upper and lower triangle pattern
a=int(input('Enter a number:'))
for i in range (1, a+1):
for j in range(1,i):
print('*', end='')
print()
for i in range(a,0,-1):
for j in range(i):
print('*', end='')
print()
OUTPUT
Program-8
Write a program for factorial of a number.
a=int(input('Enter a number:'))
f=1
i=1
while a>=i:
f*=i
i+=1
print('Factorial:',f)
OUTPUT
Program-9
Write a program to take out sum of even and odd numbers of first n natural number.
a=int(input('Enter a number:'))
sum_even=0
sum_odd=0
i=1
while n>=i:
if i%2==0:
sum_even+=i
else:
sum_odd+=i
i+=1
print('Even sum:',sum_even,'and odd sum:',sum_odd)
OUTPUT
Program-10
Write a program to make a number pattern.
a=int(input('Enter a number:'))
for i in range(1, a+1):
for j in range(1,i):
print (j, end='')
print()
for i in range(a,1,-1):
for j in range(1,i):
print(j, end='')
print()
OUTPUT
Program-11
Write a program to make an alphabet pattern with repetition.
a=int(input('Enter a number:'))
x = 65
for i in range (a+1):
y=chr (x)
for j in range(i+1):
print (y, end='')
x +=1
print()
x = 65
for i in range (a + 1, 0, - 1):
y=chr (x)
for j in range(i):
print (y, end='')
x +=1
print()
OUTPUT
Program-12
Write a program to make an alphabet pattern
a=int(input('Enter a number:'))
for i in range (a+1):
q= 65
for j in range(0,i):
print (chr(q), end='')
q+=1
print()
OUTPUT
Program-13
Write a program to make a pyramid pattern
a=int(input('Enter a number:'))
j=1
for i in range (1, a+1):
q=' '*(a-i)
print (q+j*'*', end='')
j+=2
print()
OUTPUT
Program-14
Write a program to make a number pyramid pattern
a=int(input('Enter a number:'))
q=a*2-1
b=1
for i in range (1, a+1):
for j in range(0,q):
print(end=' ')
for j in range(1,i):
print (b, end='')
b+=1
for j in range(i,0,-1):
print (b, end='')
b-=1
b=i+1
q-=1
print()
OUTPUT
Program-15
Write a program to make a number pattern without repetition.
a=int(input('Enter a number:'))
x=1
for i in range(1,a+1):
for j in range(1,i+1):
print(x,'',end='')
x+=1
print()
OUTPUT
Program-16
Write a program to split 6-digit number into three 2-digit numbers.
a=input('Enter a 6-digit number:')
if len(a)>6 or len(a)<6:
print ('ERROR!')
a=input('Enter a 6-digit number')
print('Number:',a[0:2],a[2:4],a[4:6])
OUTPUT
Program-17
Write a program to check for a perfect numbers.
a=input('Enter a number:')
sum=0
for i in range(1,a):
q=a%i
if q==0:
summ+=i
else:
continue
if sum==a:
print ('Perfect number!')
else:
print('Not a perfect number.')
OUTPUT
Program-18
Write a program to check for an Armstrong numbers.
a=int(input("Enter a number:"))
y=str(a)
temp=a
sum=0
while temp>0:
x=temp%10
sum+=x**len(y)
temp//=10
if sum==a:
print('Armstrong number')
else:
print('Not an armstrong number.')
OUTPUT
Program-19
Write a program to check for a Palindrome numbers.
a=int(input("Enter a number:"))
temp=a
a_=0
while temp>0:
x=temp%10
a_=a_*10+x
temp//=10
if a_==a:
print('Palindreome')
else:
print('Not a palindrome.')
OUTPUT
Program-20
Write a program to get Fibonacci numbers.
n=int(input('Enter a number:'))
i=0
j=1
print(i)
print(j)
for x in range(n):
k=j+1
print (k)
1,j=j,k
OUTPUT
Program-21
Write a program to take out HCF and LCM OF two numbers.
a=int(input('Enter a number:'))
b=int(input('Enter a number:'))
if a>b:
x=b
else:
x=a
for i in range (1,x+1):
if (a%i==0) and (b%i==0):
print('HCF:', hcf)
hcf=i
for j in range (1,a*b):
if(j&a==0) and (j%b==0):
1cm-j
break
print('LCM:', 1cm)
OUTPUT
Program-22
Write a function that takes a dictionary, places as an argument and display the names of those
places whose names are longer than 5 characters.
Input
def lfunc(a):
for i in a.values():
if len (i) > 5:
print (i)
return a
a={1:'LONDAN', 2:'CHINA', 3:'JAPAN'}
print(lfunc(a))
output
Program-23
Write a function that takes a string in an argument and return a tuple containing length of
each word of a string.
def lenwords(STRING):
l=[]
for word in STRING.split():
l.append(len(word))
t=tuple(l)
return t
STRING=' ilike going to school'
print(lenwords(STRING))
OUTPUT
Program-24
Write a program to calculate area of different shape
def area_of_square(x):
square = x * x
return square
def area_of_rectangle(l, b):
rectangle = l * b
return rectangle
def area_of_triangle(b, h):
triangle = 0.5 * b * h
return triangle
print("Choose the shape to calculate area:")
print("1. Square")
print("2. Rectangle")
print("3. Triangle")
a = int(input('Enter choice (1/2/3): '))
if a == 1:
x = int(input('Enter side of the square: '))
print("Area of square:", area_of_square(x))
elif a == 2:
l = int(input('Enter length of the rectangle: '))
b = int(input('Enter breadth of the rectangle: '))
print("Area of rectangle:", area_of_rectangle(l, b))
elif a == 3:
b = int(input('Enter base of the triangle: '))
h = int(input('Enter height of the triangle: '))
print("Area of triangle:", area_of_triangle(b, h))
else:
print("Invalid choice. Please choose 1, 2, or 3.")
Output
Program-25
Write a function to swap 2 numbers.
Input
def switch(x,y):
x,y=y,x
print('inside switch:',end='')
print('x=',x,'y=',y)
x=5
y=7
print('x=',x,'y=',y)
switch(x,y)
output
Program-26
Write a program to calculate two numbers and returns the result of all arithmetic operations
on these numbers.
Input
def arithmatic (x, y):
add=x+y
subtract=x-y
multiply =x*y
divide =x/y
return add, subtract, multiply, divide
x=int(input('Entre number:'))
y=int(input('Enter number:'))
print (arithmatic (x,y))
Output
Program-27
Write a program to calculate simple interest using a function interest() that can receive
principal amount, time and rate and returns calculated simple interest. Do specify default
values for rate and time as 10% and 2 years respectively.
Input
def interest (principal, time=2, rate = 0.10):
return principal*rate*time
Program-28
Write a function that generates four terms of on AP providing initial value that returns first
four terms of the series.
Input
def lfunc(a,n):
return a, a+n, a+2*n, a+3*n, a+4*n
a=int(input('enter no.:'))
n=int(input('enter no.:'))
print(lfunc(a,n))
output
Program-29
Write a program to read a text file and display the count of vowels and consonants in the file.
Input
myfile = open("Answer.txt", "r")
ch = ""
vcount = 0
ccount = 0
while ch:
ch=myfile.read(1)
if ch in ['a', 'A', 'e', 'E', 'i', 'I', 'o', '0', 'u', 'U']:
vcount = vcount + 1
else:
ccount = ccount + 1
print("Vowels in the file:", vcount)
print("Consonants in the file:", ccount)
myfile.close()
Output
Program-30
Write a program to read a txt file line by line and display each word separated by a ‘#’.
Input
myfile = open("Answer.txt", "r")
line=""
while line:
line = myfile.readline()
for word in line.split():
print(word, end = '#')
print()
myfile.close()
output
Program-31
Write a program to read a text file line by line and display each word separated by a #.
input
a=open('shelo.txt','r')
for line in a:
words=line.strip().split()
print('#'.join(words))
a.colse()
Output
Program-32
Write a program to display the size of fie is bytes
input
a=open('shelo.txt','r')
b=a.read()
c=len(b)
print(c)
a.colse()
Output
Program-33
Write a program to Create a file that hold some data
Input
a=open('shelo.txt','w')
for i in range(3):
n=input('enter here:')
b=a,write(n)
a.colse()
Output
Program-34
Write a program to function in python that counts the no. of ‘me’ or ‘my’ words that present
of in a text file (story.txt)
Input
def func():
a=open('shelo.txt','r')
count=0
for i in a.readlines():
for j in i.split():
if j=='me' or j=='my':
count=count+1
print(count)
a.colse()
Output
Program-35
Write a program to get student data, roll no., name and marks from a user and get onto a
binary file.
Input
import pickle
a=open('sheeh.txt','wb')
for i in range(3):
r=int(input('enter roll no.:'))
n=input('enter name:')
m=int(input('enter marks:'))
sum=str(r)+','+n+','+str(m)
print(sum)
b=pickle.dump(sum,a)
a.colse()
Output
Program-36
Write a program to create a csv file roll no., name, marks obtained data from user and write
into the file
Input
import csv
a=open('student.csv','w')
b=csv.writer(a)
for i in range(3):
r=int(input('enter roll no.:'))
n=input('enter name:')
m=int(input('enter marks:'))
sum=str(r)+','+n+','+str(m)
c=b.writerows(sum)
print(sum)
a.close()
Output
Program-37
Write a program that defines and calls the following user defined function:
add()-> to accept and add data of an employee to a csv file ‘record.csv’. Each record consist
of a list with field elements as empid, name and mobile to store employee id , employee
name and employee salary respectively.
Counter()->to count the number of records present in the csv file named ‘record.csv’.
Input
import csv
def ADD():
a=open("record.csv", "a", newline = "\n")
wr-csv.writer(a)
empid=int(input("Enter Employee id: "))
name=input("Enter name :: ")
mobile=int(input("Enter mobile number:: "))
1st=[empid, name, mobile]
wr.writerow (1st)
a.close()
def COUNTR():
b=open("record.csv", "r", newline="\n")
data=csv.reader(b)
d=list(data)
print (len (d))
b.close()
ADD ()
COUNTR ()
Output
Program-38
Write a program to check the divisibility of anumber and also catch the error.
Input
a=int(input("Enter no"))
b=int(input('enter division'))
try:
if a%b==0:
print("no is divisible")
except zerodivisionerror as e:
print(e)
Output
Program-39
Write a program to implement the stack operation (push and pop)
INPUT
def isEmpty(stk):
if stk==[]:
return True
else:
return False
def Pop(stk):
if isEmpty(stk):
return "Underflow"
else:
item stk.pop()
if len (stk)==0:
top=None
else:
top=len(stk)-1
return item
Stack = []
top = None
while True:
print("STACK OPERATIONS")
print("1. Push")
print("2. Pop")
print("5. Exit")
ch=int(input("Enter your choice (1-5):"))
if ch ==1:
item=int(input("Enter item :"))
Push(Stack, item)
elif ch=2:
item Pop (Stack)
if item == "Underflow":
print("Underflow! Stack is empty!")
else:
print("Popped item is", item)
OUPUT
Program-40
TABLE: PRODUCT
TABLE: BRAND
BID BRAND
M02 Dant Kanti
M03 Medimix
M04 Pepsodent
M05 Dove
a) Display product name and brand name from the tables PRODUCT and BRAND.
input
Select p.name, b.brand from PRODUCT p, BRAND b where p.BID=b.BID;
Output
d) Display the name, price, and rating of the products in descending order.
input
SELECT name,uprice,rating from product order by uprice desc,rating desc;
Output
Program-41
B. To display F_ID, Fname, Cname of those faculties who charged more than15000 as
fees.
Output
C. Display records from FACULTY table where Lastname starts with ‘M’.
Output
Program-42
Table Market
S_no Name Quantity
1 Milk powder 6
1 Washing powder 7
3 Pepsi 3
4 Cookies 5
Input
import mysql.connector
mycon = mysql.connector.connect()
host='localhost',
user='root',
password='password',
database='School')
if mycon.is_connected():
print('Database connected')
cursor = mycon.cursor()
sql = '''
CREATE TABLE IF NOT EXISTS STUDENT (
ID INT PRIMARY KEY,
Name CHAR(10),
Stream CHAR(10),
AvgMark FLOAT,
Grade CHAR(2),
Class CHAR(5))'''
cursor.execute(sql)
sql = '''
INSERT INTO STUDENT (ID, Name, Stream, AvgMark, Grade, Class)
VALUES
(1, 'Karan', 'Medical', 78.5, 'B', '128'),
(2, 'Divakar', 'Commerce', 89.2, 'A', '11C'),
(3, 'Divya', 'Commerce', 68.6, 'C', '12C'),
(4, 'Arun', 'Computers', 89.9, 'A', '12A'),
(5, 'Sabina', 'Medical', 83.3, 'B', '128') '''
cursor.execute(sql)
mycon.commit()
cursor.execute('SELECT * FROM STUDENT')
data = cursor.fetchall()
for rec in data:
print(rec)
mycon.close()
output
Program-44
Write a program to connect python with mysql using database connectivity and perform the
following operations in database:
a) Count the number of records in each stream and display it b) Display the number of
students who have secured ‘A’Grade c) Add a new column called Rank in the table.
Input
import mysql.connector
mycon = mysql.connector.connect(
host='localhost',
user='root',
password='password',
database='School')
if mycon.is_connected():
print('Database connected')
cursor = mycon.cursor()
sql = 'SELECT Stream, COUNT(*) FROM STUDENT GROUP BY Stream'
cursor.execute(sql)
data = cursor.fetchall()
print("Answer for a):")
for rec in data:
print(rec)
mycon = mysql.connector.connect(
host='localhost',
user='root',
password='password',
database='School')
if mycon.is_connected():
print('Database connected')
cursor = mycon.cursor()
output