Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
22 views27 pages

Aryan Practical File New

This document is a practical file for Computer Science submitted by a student named Aryan Sartaj Nirwal Singh from Holy Child Public School, Rewari. It includes various Python programs and SQL queries demonstrating concepts such as palindrome checking, variable scope, string analysis, file handling, and database operations. The document is structured with acknowledgments, certificates, and multiple practical exercises along with their source code and outputs.

Uploaded by

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

Aryan Practical File New

This document is a practical file for Computer Science submitted by a student named Aryan Sartaj Nirwal Singh from Holy Child Public School, Rewari. It includes various Python programs and SQL queries demonstrating concepts such as palindrome checking, variable scope, string analysis, file handling, and database operations. The document is structured with acknowledgments, certificates, and multiple practical exercises along with their source code and outputs.

Uploaded by

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

HOLY CHILD PUBLIC SCHOOL

REWARI

PRACTICAL FILE
ON
COMPUTER SCIENCE
CODE: 083
SESSION: 2024-25
SUBMITTED BY:
STUDENT NAME:--ARYAN
SARTAJNIRWAL
SINGH
ROLL NO. :-- 17714972
CLASS & SEC. :--12th Science A1
SUBMITTED TO: SAURABH SIR
Acknowledgement
I would like to express my
gratitude toward to my Computer
Science teacher Saurabh Sir for his
valuable guidance and nonstop
support during this project. As well
as, I am grateful to our principal
Vimmi Mam for providing me with
the beautiful opportunity to work
on this Project.
CERTIFICATE
It is certified that Aryan
S A R T A JNirwal
S I N G H of class
XII has completed this project under the
guidance and supervision of Saurabh
Sir with great diligence. The project for
the subject of Info. Technology is up to
the standards of the Central Board of
Secondary Education and can be sent
for evaluation.

Teacher’s Signature

---------------------------
Practical No-1
# Write a program to check a number whether it is palindrome or not.
SOURCE CODE:
def number():
num=int(input("Enter a number : "))
n=num
res=0
while num>0:
rem=num%10
res=rem+res*10
num=num//10
if res==n:
print("Number is Palindrome")
else:
print("Number is not Palindrome")
number()

Output -
Practical No-2
# Example of Global and Local variables in function

x = "global "
def display():
global x
y = "local"
x=x*2
print(x)
print(y)
display()

Output -

global global
local
Practical No-3
# Python program to count the number of vowels, consonants, digits and
special characters in a string
def st():
str = input(“Enter the string : “)
vowels = 0
digits = 0
consonants = 0
spaces = 0
symbols = 0
str = str.lower()
for i in range(0, len(str)):
if (str[i] == ‘a’or str[i] == ‘e’ or str[i] == ‘i’ or str[i] == ‘o’ or str[i] == ‘u’):
vowels = vowels + 1
elif ((str[i] >= ‘a’and str[i] <= ‘z’)):
consonants = consonants + 1
elif ( str[i] >= ‘0’ and str[i] <= ‘9’):
digits = digits + 1
elif (str[i] ==’ ‘):
spaces = spaces + 1
else:
symbols = symbols + 1
print(“Vowels: “, vowels)
print(“Consonants: “, consonants)
print(“Digits: “, digits)
st()
print(“White spaces: “, spaces)
print(“Symbols : “, symbols)

Output -
Enter the string : 123 hello world $%&45
Volwels: 3
Consontants: 7
Digits: 5
White spaces: 3
Symbols: 3
Practical No-4
# Python Program to add marks and calculate the grade of a student
def grade():
total=int(input("Enter the maximum mark of a subject: "))
sub1=int(input("Enter marks of the first subject: "))
sub2=int(input("Enter marks of the second subject: "))
sub3=int(input("Enter marks of the third subject: "))
sub4=int(input("Enter marks of the fourth subject: "))
sub5=int(input("Enter marks of the fifth subject: "))
average=(sub1+sub2+sub3+sub4+sub5)/5
print("Average is ",average)
percentage=(average/total)*100
print("According to the percentage, ")
if percentage >= 90:
print("Grade: A")
elif percentage >= 80 and percentage < 90:
print("Grade: B")
elif percentage >= 70 and percentage < 80:
print("Grade: C")
elif percentage >= 60 and percentage < 70:
print("Grade: D")
else:
print("Grade: E")
grade()
Output -

Enter the maximum mark of a subject: 10


Enter marks of the first subject: 8
Enter marks of the second subject: 7
Enter marks of the third subject: 9
Enter marks of the fourth subject: 6
Enter marks of the fifth subject: 8
Average is 7.6
According to the percentage,
Grade: C
Practical No-5
# Generating a List of numbers Using For Loop
import random
randomlist = []
for i in range(0,5):
n = random.randint(1,30)
randomlist.append(n)
print(randomlist)

Output -

[10, 5, 21, 1, 17]


Practical No-6
# Write a program to read a text file line by line and display each word
separated by '#'.
def line():
f=open("Mydoc.txt",'r')
for i in f:
s= i.split()
for j in s:
print(j + '#',end ='')
print()
f.close()
line()

Output -
Text in file:
hello how are you?
python is case-sensitive language.
Output in python shell:
hello#how#are#you?#python#is#case-sensitive#language.#
Practical No-7
# Read a text file and display the number of vowels/ consonants/ uppercase/
lowercase characters and other than character and digit in the file.
def cnt():
f=open("Mydoc1.txt",'r')
a = f.read()
vow = 0
count_con = 0
count_low = 0
count_up = 0
count_digit = 0
count_other = 0

for i in a:
if i.isupper():
count_up +=1
if i.islower():
count_low += 1
if i in 'aeiouAEIOU':
vow += 1
if i.isalpha():
count_con += 1
if i.isdigit():
count_digit += 1
if not i.isalnum() and ch !=' ' and ch !='\n':
count_other += 1
print("Digits",count_digit)
print("Vowels: ",vow)
print("Consonants: ",count_con-count_vow)
print("Upper Case: ",count_up)
print("Lower Case: ",count_low)
print("other than letters and digit: ",count_other)

f.close()

cnt()
Practical No-8
# Remove all the lines that contain the character `a' in a file and write it to
another file
def remove():
f1 = open("Mydoc.txt")
f2 = open("copyMydoc.txt","w")
for i in f1:
if 'a' not in i:
f2.write(i)
f1.close()
f2.close()
f2= open("copyMydoc.txt","r")
print(f2.read())
remove()
Practical No-9
# Create a binary file with the name and roll number. Search for a given roll
number and display the name, if not found display appropriate message.
import pickle p

def Writerecord(sroll,sname):
Myfile=open('StudentRecord1.dat','ab'):
srecord={"SROLL":sroll,"SNAME":sname}
p.dump(srecord,Myfile)

def Readrecord():
Myfile=open('StudentRecord1.dat','rb'):
while True:
try:
rec=p.load(Myfile)
print(rec['SROLL'] ,rec['SNAME'])
except EOFError:
break
def Input():
n=int(input("How many records you want to create :"))
for i in range(n):
sroll=int(input("Enter Roll No: "))
sname=input("Enter Name: ")
Writerecord(sroll,sname)

def SearchRecord(roll):
Myfile=open('StudentRecord1.dat','rb'):
while True:
try:
rec=p.load(Myfile)
if rec['SROLL']==roll:
print("Roll NO:",rec['SROLL'])
print("Name:",rec['SNAME'])

except EOFError:
print("Record not find")
break

def main():

while True:
print('1.Insert Records')
print('2.Dispaly Records')
print( '3. Search Records (By RollNo)')
print('0.Exit (Enter 0 to exit)')
c=int(input('Enter Your Choice: '))
if c==1:
Input()
elif c==2:
Readrecord()
elif c==3:
r=int(input("Enter a Rollno to be Search: "))
SearchRecord(r)
else:
break
main()
Practical No-10
# Write a program to perform read and write operation onto a student.csv file
having fields as roll number, name, stream and percentage.
import csv as c
csvf=open('Student_Details.csv','w'):
writecsv=c.writer(csvf)
a='y'
while a.lower()=='y':
rl=int(input("Enter Roll No.: "))
n=input("Enter Name: ")
p=float(input("Enter Percentage: "))
r=input("Enter Remarks: ")
writecsv.writerow([rl,n,p,r])
print(" Data saved in Student Details file..")
a=input("Want add more record(y/n)..")

fileobject=open('Student_Details.csv','r'):
readcsv=c.reader(fileobject)
for i in readcsv:
print(i)
Practical No-11
# Write a python program to implement a stack using a list data-structure.
def isempty(stk):
if stk==[]:
return True
else:
return False

def push(stk,item):
stk.append(item)
top=len(stk)-1

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

def peek(stk):
if isempty(stk):
return "underflow"
else:
top=len(stk)-1
return stk[top]

def display(stk):
if 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])

#Driver Code

def main():
stk=[]
top=None
while True:
print('''stack operation
1.push
2.pop
3.peek
4.display
5.exit''')
c=int (input('enter choice:'))
if c==1:
item=int(input('enter item:'))
push(stk,item)
elif c==2:
item=pop(stk)
if item=="underflow":
print('stack is underflow')
else:
print('poped')
elif c==3:
item=peek(stk)
if item=="underflow":
print('stack is underflow')
else:
print('top most item is:',item)
elif c==4:
display(stk)
elif c==5:
break
else:
print('invalid')
exit()
main()
Practical No-12

SQL
Create a table EMPLOYEE with constraints
SOLUTION
Step-1 Create a database:
CREATE DATABASE Bank;
Step-2 Display the databases
SHOW DATABASES;
Step-3: Enter into database
Use Bank;
Step-4: Create the table EMPLOYEE
create table Employee(Ecode int primary key,Ename varchar(20) NOT NULL,
Dept varchar(15),City varchar(15), sex char(1), DOB date, Salary float(12,2));

Insert data into the table


SOLUTION
insert into Employee values(1001,"Atul","Production","Vadodara","M","1992-
10-23",23000.50);
Query OK, 1 row affected (0.11 sec)
Note: Insert more rows as per above insert command.

Add a new column in a table.


SOLUTION
ALTER TABLE EMPLOYEE ADD address varchar(50);
Change the data-type and size of an existing column.
SOLUTION
ALTER TABLE EMPLOYEE MODIFY city char(30);
Write SQL queries using SELECT, FROM, WHERE clause based on
EMPLOYEE table.
1. List the name of female employees in EMPLOYEE table.
Solution:-
SELECT Ename FROM EMPLOYEE WHERE sex=’F’;
2. Display the name and department of those employees who work in surat
and salary is greater than 25000.
Solution:-
SELECT Ename, Dept FROM EMPLOYEE WHERE city=’surat’ and salary > 25000;
3. Display the name of those female employees who work in Mumbai.
Solution:-
SELECT Ename FROM EMPLOYEE WHERE sex=’F’ and city=’Mumbai’;
4. Display the name of those employees whose department is marketing or
RND.
Solution:-
SELECT Ename FROM EMPLOYEE WHERE Dept=’marketing’ OR Dept=’RND’
5. List the name of employees who are not males.
Solution:-
SELECT Ename, Sex FROM EMPLOYEE WHERE sex!=’M’;
Queries using DISTINCT, BETWEEN, IN, LIKE, IS NULL, ORDER BY,
GROUP BY, HAVING
A. Display the name of departments. Each department should be displayed
once.
SOLUTION
SELECT DISTINCT(Dept) FROM EMPLOYEE;
B. Find the name and salary of those employees whose salary is between
35000 and 40000.
SOLUTION
SELECT Ename, salary FROM EMPLOYEE WHERE salary BETWEEN 35000 and
40000;
C. Find the name of those employees who live in guwahati, surat or jaipur city.
SOLUTION
SELECT Ename, city FROM EMPLOYEE WHERE city IN(‘Guwahati’,’Surat’,’Jaipur’);
D. Display the name of those employees whose name starts with ‘M’.
SOLUTION
SELECT Ename FROM EMPLOYEE WHERE Ename LIKE ‘M%’;
E. List the name of employees not assigned to any department.
SOLUTION
SELECT Ename FROM EMPLOYEE WHERE Dept IS NULL;
F. Display the list of employees in descending order of employee code.
SOLUTION
SELECT * FROM EMPLOYEE ORDER BY ecode DESC;
G. Find the average salary at each department.
SOLUTION
SELECT Dept, avg(salary) FROM EMPLOYEE group by Dept;
H.Find maximum salary of each department and display the name of that
department which has maximum salary more than 39000.
SOLUTION
SELECT Dept, max(salary) FROM EMPLOYEE group by Dept HAVING
max(salary)>39000;
Queries for Aggregate functions- SUM( ), AVG( ), MIN( ), MAX( ), COUNT( )
a. Find the average salary of the employees in employee table.
Solution:-
SELECT avg(salary) FROM EMPLOYEE;
b. Find the minimum salary of a female employee in EMPLOYEE table.
Solution:-
SELECT Ename, min(salary) FROM EMPLOYEE WHERE sex=’F’;
c. Find the maximum salary of a male employee in EMPLOYEE table.
Solution:-
SELECT Ename, max(salary) FROM EMPLOYEE WHERE sex=’M’;
d. Find the total salary of those employees who work in Guwahati city.
Solution:-
SELECT sum(salary) FROM EMPLOYEE WHERE city=’Guwahati’;
e. Find the number of tuples in the EMPLOYEE relation.
Solution:- SELECT count(*) FROM EMPLOYEE
Practical No-13
# Write a program to connect Python with MySQL using database connectivity
and perform the following operations on data in database: Fetch, Update and
delete the data.
A. CREATE A TABLE
SOLUTION
import mysql.connector
demodb = mysql.connector.connect(host="localhost", user="root",
passwd="computer", database="EDUCATION")
democursor=demodb.cursor( )
democursor.execute("CREATE TABLE STUDENT (admn_no int primary key,
sname varchar(30), gender char(1), DOB date, stream varchar(15), marks
float(4,2))")
B. INSERT THE DATA
SOLUTION
import mysql.connector
demodb = mysql.connector.connect(host="localhost", user="root",
passwd="computer", database="EDUCATION")
democursor=demodb.cursor( )
democursor.execute("insert into student values (%s, %s, %s, %s, %s, %s)",
(1245, 'Arush', 'M', '2003-10-04', 'science', 67.34))
demodb.commit( )
C. FETCH THE DATA
SOLUTION
import mysql.connector
demodb = mysql.connector.connect(host="localhost", user="root",
passwd="computer", database="EDUCATION")
democursor=demodb.cursor( )
democursor.execute("select * from student")
for i in democursor:
print(i)
D. UPDATE THE RECORD
SOLUTION
import mysql.connector
demodb = mysql.connector.connect(host="localhost", user="root",
passwd="computer", database="EDUCATION")
democursor=demodb.cursor( )
democursor.execute("update student set marks=55.68 where admn_no=1356")
demodb.commit( )
E. DELETE THE DATA
SOLUTION
import mysql.connector
demodb = mysql.connector.connect(host="localhost", user="root",
passwd="computer", database="EDUCATION")
democursor=demodb.cursor( )
democursor.execute("delete from student where admn_no=1356")
demodb.commit()

You might also like