Practical File
Practical File
SESSION: 2022-23
COMPUTER SCIENCE PRACTICAL FILE
NAME :
ROLL NO. :
CLASS :
SECTION :
ATSBV
CHATTARPUR
DELHI - 110074
S. Name of Practical
No.
1 Write a program to check a number whether it is palindrome or not.
2 Write a program to display ASCII code of a character and vice versa.
3 Write a python program by defining a function to sum the sequence given below.
Take the input n from the user. 1+1/1!+1/2!+1/3!+⋯+1/n!
4 Write a program to read a text file line by line and display each word separated
by '#'
5 Write a program to count the number of vowels present in a text file.
6 Write a program to count number of words in a file.
7 Write a program to count the number of times the occurrence of 'is' word in a
text file.
8 Write a program to write those lines which have the character 'p' from one text
file to another text file.
9 Create a binary file with name and roll number of student and display the data by
reading the file.
10 Write a program to search a record using its roll number and display the name of
student. If record not found then display appropriate message.
11 Write a program to update the name of student by using its roll number in a
binary file.
12 Write a program to delete a record from binary file.
13 Write a program to perform read and write operation with .csv file.
14 Write a menu based program to perform the push , pop and display operation on
stack in python.
15 Create a table EMPLOYEE with constraints.
1. Create a database:
2. Display the databases
3. Enter into database
4. Create the table EMPLOYEE
16 Write a sql query for inserting a data into the table, Adding a new column in a
table and changing the data type and column size.
17 Write SQL queries using SELECT, FROM, WHERE clause based on EMPLOYEE
table.
18 Write SQL Queries using DISTINCT, BETWEEN, IN, LIKE, IS NULL, ORDER BY,
GROUP BY, HAVING.
19 Write SQL Queries for Aggregate functions- SUM( ), AVG( ), MIN( ), MAX( ),
COUNT( )
20 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.
Program 1. Write a program to check a number whether it is palindrome or not.
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")
Output:
________________________________________________________________
1|Page
Program 2. Write a program to display ASCII code of a character and vice versa.
var=True
while var:
choice=int(input("Press-1 to find the ordinal value of a character \nPress-2 to find a
character of a value\n"))
if choice==1:
ch=input("Enter a character : ")
print(ord(ch))
elif choice==2:
val=int(input("Enter an integer value: "))
print(chr(val))
else:
print("You entered wrong choice")
print("Do you want to continue? Y/N")
option=input()
print("Do you want to continue? Y/N")
option=input()
if option=='y' or option=='Y':
var=True
else:
var=False
Output:
________________________________________________________________
2|Page
Program 3. Write a python program to sum the sequence given below. Take the input n
from the user. 1+1/1!+1/2!+1/3!+⋯+1/n!
def fact(x):
j=1
res=1
while j<=x:
res=res*j
j=j+1
return res
while i<=n:
f=fact(i)
sum=sum+1/f
i+=1
print(sum)
Output:
________________________________________________________________
3|Page
Program 4. Write a program to read a text file line by line and display each word
separated by '#'.
fin=open("D:\\python programs\\Book.txt",'r')
L1=fin.readlines( )
s=' '
for i in range(len(L1)):
L=L1[i].split( )
for j in L:
s=s+j
s=s+'#'
print(s)
fin.close( )
Output:
________________________________________________________________
4|Page
Program 5. Write a program to count the number of vowels present in a text file.
fin=open("D:\\python programs\\MyBook.txt",'r')
str=fin.read( )
count=0
for i in str:
if i=='a' or i=='e' or i=='i' or i=='o' or i=='u':
count=count+1
print(count)
Output:
________________________________________________________________
5|Page
Program 6. Write a program to count number of words in a file.
fin=open("D:\\python programs\\Story.txt",'r')
str=fin.read( )
L=str.split()
count_words=0
for i in L:
count_words=count_words+1
print(count_words)
Output:
________________________________________________________________
6|Page
Program 7. Write a program to count the number of times the occurrence of 'is' word in a
text file.
fin=open("D:\\python programs\\Book.txt",'r')
str=fin.read( )
L=str.split( )
count=0
for i in L:
if i=='is':
count=count+1
print(count)
fin.close( )
Output:
________________________________________________________________
7|Page
Program 8. Write a program to write those lines which have the character 'p' from one
text file to another text file.
fin=open("E:\\book.txt","r")
fout=open("E:\\story.txt","a")
s=fin.readlines( )
for j in s:
if 'p' in j:
fout.write(j)
fin.close()
fout.close()
Output:
________________________________________________________________
8|Page
Program 9. Create a binary file with name and roll number of student and display the data
by reading the file.
import pickle
def writedata( ):
list =[ ]
while True:
roll = input("Enter student Roll No:")
sname = input("Enter student Name :")
student = {"roll":roll,"name":sname}
list.append(student)
choice= input("Want to add more record(y/n) :")
if(choice=='n'):
break
file = open("student.dat","wb")
pickle.dump(list,file)
file.close( )
def readdata( ):
file = open("student.dat", "rb")
list = pickle.load(file)
print(list)
file.close( )
choice=int(input( ))
if choice==1:
writedata( )
elif choice==2:
readdata( )
else:
print("You entered invalid value")
Output:
________________________________________________________________
9|Page
Program 10. Write a program to search a record using its roll number and display the
name of student. If record not found then display appropriate message.
import pickle
roll = input('Enter roll number that you want to search in binary file :')
file = open("student.dat", "rb")
l1 = pickle.load(file)
for x in l1:
if roll in x['roll']:
print("Name of student is:", x['name'])
break else:
file.close( )
Output:
________________________________________________________________
Enter roll number that you want to search in binary file :102
Name of student is: Hitesh
10 | P a g e
Program 11. Create a simple calculator program that takes two numbers as input.
Implement excep on handling to handle cases like division by zero.
Solu on:
try:
num1 = int(input("Enter First Number: "))
num2 = int(input("Enter Second Number: "))
print(result)
except ValueError as e:
print("Invalid Input Please Input Integer...")
except ZeroDivisionError as e:
print(e)
Output:
Solu on:
try:
print(person," is ",ages[person]," years old.")
except KeyError:
print("Age of", person," is unknown.")
Output:
=== RESTART: C:\Users\User\AppData\Local\Programs\Python\Python311\default.py ==
Get age for: Ashok
Ashok is 30 years old.
else:
print('roll number does not exist')
file.close( )
Output:
________________________________________________________________
Enter roll number whose name you want to update in binary file :106
Enter new name: Naresh Record Updated
11 | P a g e
Program 12. Write a program to delete a record from binary file.
import pickle
roll = input('Enter roll number whose record you want to delete:')
file = open("student.dat", "rb+")
list = pickle.load(file)
found = 0
lst = []
for x in list:
if roll not in x['roll']:
lst.append(x)
else:
found = 1
if found == 1:
file.seek(0)
pickle.dump(lst, file)
print("Record Deleted ")
else:
print('Roll Number does not exist')
file.close()
Output:
________________________________________________________________
12 | P a g e
Program 13. Write a program to perform read and write operation with .csv file.
import csv
def readcsv():
with open('C:\\Users\\ViNi\\Downloads\\data.csv','rt')as f:
data = csv.reader(f) #reader function to generate a reader object
for row in data:
print(row)
def writecsv( ):
with open('C:\\Users\\ViNi\\Downloads\\data.csv', mode='a', newline='') as file:
writer = csv.writer(file, delimiter=',', quotechar='"') #write new record in file
writer.writerow(['4', 'Devansh', 'Arts', '404'])
print("Press-1 to Read Data and Press-2 to Write data: ")
a=int(input())
if a==1:
readcsv()
elif a==2:
writecsv()
else:
print("Invalid value")
Output:
________________________________________________________________
13 | P a g e
Program 14. Write a menu based program to perform the push , pop and display
operation on stack in python.
def push (country_name):
country_name.append(cname)
if country_name !=[ ]:
print(country_name.pop())
else:
print("Stack is empty")
def show(country_name):
print(country_name)
stack=[ ]
choice=' '
push(stack)
pop(stack)
show(stack)
break
else:
14 | P a g e
Output:
________________________________________________________________
15 | P a g e
Program 15. Create a table EMPLOYEE with constraints.
Step-1 Create a database:
CREATE DATABASE Bank;
Output:
________________________________________________________________
16 | P a g e
Program 16. Write a sql query for inserting a data into the table, Adding a new column in a
table and changing the data type and column size.
1. Insert data into the table
Query:
insert into Employee values(1001,"Atul","Production","Vadodara","M","1992- 10-
23",23000.50);
Output:
________________________________________________________________
Query OK, 1 row affected (0.11 sec)
17 | P a g e
Program 17. Write SQL queries using SELECT, FROM, WHERE clause based on EMPLOYEE
table.
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;
18 | P a g e
Program 18. Queries using DISTINCT, BETWEEN, IN, LIKE, IS NULL, ORDER BY, GROUP BY,
HAVING.
1. Display the name of departments. Each department should be displayed once.
Solution : SELECT DISTINCT(Dept) FROM EMPLOYEE;
2. 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;
3. 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’);
4. Display the name of those employees whose name starts with ‘M’.
Solution : SELECT Ename FROM EMPLOYEE WHERE Ename LIKE ‘M%’;
8. 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;
19 | P a g e
Program 19. Queries for Aggregate functions- SUM( ), AVG( ), MIN( ), MAX( ), COUNT( )
4. Find the total salary of those employees who work in Guwahati city .
Solution: SELECT sum(salary) FROM EMPLOYEE WHERE city=’Guwahati’;
20 | P a g e
Program 20. 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.
#CREATE A TABLE
import mysql.connector
mycursor=mydb.cursor( )
mycursor= mydb.cursor( )
democursor.execute("insert into student values (%s, %s, %s, %s, %s, %s)", (1245, 'Arush', 'M', '2003-
10-04', 'science', 67.34))
mydb.commit( )
mycursor= mydb.cursor( )
for i in mycursor:
print(i)
21 | P a g e
#UPDATE THE RECORD
import mysql.connector
mycursor= mydb.cursor( )
mydb.commit( )
mycursor= mydb.cursor( )
mydb.commit( )
22 | P a g e