0% found this document useful (0 votes)
3 views41 pages

Practical

The document contains a practical file for a Computer Science course, detailing various Python programs and SQL queries for the academic year 2025-26. It includes code for calculating factorials, checking palindromes, generating Fibonacci sequences, and handling file operations, as well as SQL commands for database management tasks. Each program is presented with its code and expected output, serving as a comprehensive guide for students.

Uploaded by

jkverse07
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)
3 views41 pages

Practical

The document contains a practical file for a Computer Science course, detailing various Python programs and SQL queries for the academic year 2025-26. It includes code for calculating factorials, checking palindromes, generating Fibonacci sequences, and handling file operations, as well as SQL commands for database management tasks. Each program is presented with its code and expected output, serving as a comprehensive guide for students.

Uploaded by

jkverse07
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

Computer Science

Practical File
2025-26
Name:
Class:
Roll Number:
PYTHON-
1. Program to find factorial of a number.
Code-
number=int(input('Enter a number: '))
x=1
for i in range(number):
x*=i+1
print(x)
Output-
2. Program to check if a number is a palindrome using a user-defined
function.
Code-
def palindrome(num):
x=y=0
z=num
while True:
if z!=0:
x=z%10
y=x+(y*10)
z//=10
else:
break
if y==num:
print('The number is a palindrome.')
else:
print('The number is not a palindrome.')
num=int(input('Enter a number:'))
palindrome(num)
Output-
3. Program to generate Fibonacci sequence.
Code-
loop=int(input('Enter how many numbers of the Fibonacci sequence you
want: '))
x=1
y=1
z=0
print('The Fibonacci sequence for',loop,'numbers is:')
print(1)
for i in range(loop-1):
print(x)
z=x
x+=y
y=z
Output-
4. Program to count the number of vowels, consonants, digits and white
spaces in a string.
Code-
x=input('Enter a string: ')
a=b=c=d=0
for i in x:
if i in 'AEIOUaeiou':
a+=1
elif [Link]() and i not in 'AEIOUaeiou':
b+=1
elif [Link]():
c+=1
elif [Link]():
d+=1
print('Number of vowels:',a,'\nNumber of consonants:',b,'\nNumber of
digits:',c,'\nNumber of white spaces:',d)
Output-
5. Program to remove all duplicates from a list.
Code-
list1=eval(input('Enter a list: '))
list2=[]
for i in list1:
if i not in list2:
[Link](i)
print('The list with unique values is:',list2,sep='\n')
Output-
6. Program to sort a list of tuples based on the second element.
Code-
list1=eval(input('Enter a list of tuples with integers: '))
list2=[]
list3=[]
x=z=0
y=len(list1)
for i in list1:
[Link](i[1])
for i in range(y):
x=min(list2)
z=[Link](x)
[Link](list1[z])
list2[z]=max(list2)+1
x=0
print('Ordered list based on second element:',list3,sep='\n')
Output-
7. Program to count the frequency of each word in a string using dictionary.
Code-
words=input('Enter string: ')
dict1={}
list1=[Link]()
for i in list1:
if i in dict1:
dict1[i]=[Link](i)+1
else:
dict1[i]=1
print('Dictionary with frequencies of the words:',dict1,sep='\n')
Output-
8. Program to sort dictionary by values.
Code-
dict1=eval(input('Enter a dictionary with integers as values: '))
x=list([Link]())
y=list([Link]())
z=n=0
dict2={}
for i in range(len(y)):
z=min(y)
n=[Link](z)
dict2[x[n]]=z
y[n]=max(y)+1
n=0
print('Sorted dictionary by values:',dict2,sep='\n')
Output-
9. Program to count number of lines, words and characters in a text file.
Code-
file=open('[Link]','r')
rfile=[Link]()
x=[Link]('\n')
lines=len(x)
a=[Link]('\n')
b=[Link](' ')
words=0
if [Link](' \n'):
words=a+b-1
else:
words=a+b
characters=0
for i in rfile:
if i != '\n':
characters+=1
print('File:\n',rfile,'\nNumber of lines:',lines-1,'\nNumber of
words:',words,'\nNumber of characters:',characters,sep='')
Output-
10. Program to read a text file and print only those lines that contain the
word “Python”.
Code-
file=open('[Link]','r')
rfile=[Link]()
x=[Link]('\n')
for i in x:
if [Link]('Python')>=1:
print(i)
Original file-
Python is a programming language
I like Python
I don't like Java
Python has an interactive shell
Output-
11. Program to copy the content of one file to another.
Code-
file=open('[Link]','r')
rfile=[Link]()
file2=open('[Link]','w')
[Link](rfile)
[Link]()
file3=open('[Link]','r')
rfile3=[Link]()
print('Original file:\n',rfile,'\nNew file:\n',rfile3,sep='')
[Link]()
[Link]()
Output-
12. Program to display the longest word from a text file.
Code-
file=open('[Link]','r')
rfile=[Link]()
x=0
y=''
z=[Link]('\n')
for i in z:
a=[Link](' ')
for j in a:
if len(j)>x:
x=len(j)
y=j
print('Longest word in file:',y)
Output-
13. Menu based program for binary file.
Code-
import pickle as p
def write():
file=open('[Link]','wb')
lst=[]
while True:
a=input('Do you want to continue with input("y" or "n"): ')
if a in 'Yy':
name1=input('Enter name: ')
class1=int(input('Enter class: '))
number1=int(input('Enter roll number: '))
[Link]([name1,number1,class1])
elif a in 'Nn':
print('******************************')
break
[Link](lst,file)
[Link]()
def search():
file=open('[Link]','rb')
rfile=[Link](file)
x=0
y=int(input('Enter the roll no: '))
z=0
for i in rfile:
if i[1]==y:
x=1
z=i
if x==1:
print('Input is in the file\n',z,'\n******************************',sep='')
else:
print('Input is not in the file\n******************************')
[Link]()
def read():
file=open('[Link]','rb')
rfile=[Link](file)
for i in rfile:
print(i)
print('******************************')
[Link]()
def update():
file=open('[Link]','rb')
rfile=[Link](file)
[Link]()
wfile=open('[Link]','wb')
x=0
lst=[]
z=int(input('Enter the roll number: '))
for i in rfile:
if i[1]==z:
x=1
print('Input is in the file\n******************************')
name1=input('Enter name: ')
class1=int(input('Enter class: '))
[Link]([name1,i[1],class1])
else:
[Link](i)
[Link](lst,wfile)
if x==0:
print('Input is not in the file\n******************************')
[Link]()
def append():
file=open('[Link]','rb')
rfile=[Link](file)
[Link]()
wfile=open('[Link]','wb')
while True:
x=input('Do you want to continue with input("y" or "n"): ')
if x in 'Yy':
name1=input('Enter name: ')
class1=int(input('Enter class: '))
number1=int(input('Enter roll number: '))
[Link]([name1,number1,class1])
else:
print('******************************')
break
[Link](rfile,wfile)
[Link]()
def delete():
file=open('[Link]','rb')
rfile=[Link](file)
[Link]()
wfile=open('[Link]','wb')
lst=[]
x=0
y=int(input('Enter the roll number:'))
for i in rfile:
if i[1]==y:
x=1
print('Input has been deleted\n******************************')
else:
[Link](i)
if x==0:
print('Input not found\n******************************')
[Link](lst,wfile)
[Link]()
while True:
f1=int(input('Enter the number corresponding to the function you want to
use\n1->Write\n2->Read\n3->Search\n4->Append\n5->Update\n6-
>Delete\n7->Exit\n'))
if f1==1:
write()
elif f1==2:
read()
elif f1==3:
search()
elif f1==4:
append()
elif f1==5:
update()
elif f1==6:
delete()
elif f1==7:
break
Output-
14. Program to demonstrate try-except block for handling ZeroDivisionError
and ValueError.
Code-
while True:
try:
dividend=int(input('Enter the dividend in integer: '))
break
except ValueError:
print('Input is invalid. Try again.')
while True:
try:
divisor=int(input('Enter the divisor in integer: '))
break
except ValueError:
print('Input is invalid. Try again.')
try:
quotient=dividend/divisor
print('Answer is:',quotient)
except ZeroDivisionError:
print('Answer is undefined.')
Output-
15. Program to create a user-defined exception for invalid age.
Code-
class InvalidAgeError(Exception):
pass
while True:
try:
age=float(input('Enter age: '))
if age<1:
raise InvalidAgeError
else:
break
except ValueError:
print('Age is invalid. Try again.')
except InvalidAgeError:
print('Age is invalid. Try again.')
Output-
16. Write a menu based program for csv.
Code-
import csv
def write():
f=[]
a=open('[Link]','a',newline='')
ch=[Link](a)
b=int(input('Enter no of enteries you want to enter: '))
for i in range(b):
w=input('Enter Book name: ')
x=input('Enter Author name: ')
y=int(input('Enter year publication: '))
z=int(input('Enter no of copies avalaible: '))
[Link]([w,x,y,z])
[Link](f)
[Link]()
def show():
a=open('[Link]','r')
b=[Link](a)
for i in b:
print(i)
[Link]()
def search():
a=open('[Link]','r')
b=[Link](a)
fal=False
x=input('Enter the name of book you want to search: ')
for i in b:
if i[0]==x:
print('Book found')
print(i)
fal=True
if fal==False:
print('Book not found')
[Link]()
print('This program will allow you to perform various functions on csv file')
while True:
a=int(input('[Link]\[Link]\[Link]\[Link]\n'))
if a==1:
write()
elif a==2:
show()
elif a==3:
search()
elif a==4:
break
else:
print('Invalid input')
Output-
17. Write a menu-driven program to implement a stack using functions
push, pop, and display.
Code-
a=[]
def push():
z=int(input('Enter employee no.: '))
y=input('Enter employee name: ')
g=int(input('Enter salary: '))
t=(z,y,g)
[Link](t)
def pop():
print('The popped data is',[Link]())
def display():
for i in a:
print(i)
while True:
n=int(input('[Link]\[Link]\[Link]\[Link]\n'))
if n==1:
push()
elif n==2:
pop()
elif n==3:
display()
elif n==4:
break
Output-
18. Add a record in table using python in mysql.
Code-
import [Link] as ms
con = [Link]( host = 'localhost',user = 'root',password =
'admin',database = 'SHOP')
cur = [Link]()
a = input("Enter Product ID:")
b = input("Enter Product Name:")
c = input("Enter Manufacturer:")
d = int(input("Enter price of product:"))
query='insert into products values(%s,%s,%s,%s)'
[Link](query,(a,b,c,d))
[Link]()
Output-
19. Display all records of a table of mysql using python.
Code-
import [Link] as ms
con = [Link]( host = 'localhost',user = 'root',password =
'admin',database = 'SHOP')
cur = [Link]()
[Link]('select * from products')
data=[Link]()
for i in data:
print(i)
Output-
20. Modify the price of a given product as entered by the user in mysql by
using python.
Code-
import [Link] as ms
con = [Link]( host = 'localhost',user = 'root',password =
'admin',database = 'SHOP')
cur = [Link]()
a = input("Enter the product ID:")
b = int(input("Enter the new price of product:"))
query = "Update products set Price = %s where P_ID = %s"
[Link](query,(b,a))
[Link]()
[Link]()
Output-
21. Delete a product from the table in mysql using the product ID entered
by the user through python.
Code-
import [Link] as ms
con = [Link]( host = 'localhost',user = 'root',password = 'admin',\
database = 'SHOP')
cur = [Link]()
a = input("Enter the product ID of the product you want to delete:")
query = "DELETE from products where P_ID = %s"
[Link](query,(a,))
[Link]()
[Link]()
Output-
SQL QUERIES-
Q1. Consider the table Family given below.

Write commands in SQL for the following-


a) Create the above table.

b) To insert the given data in the above table.

c) To display the name of all those where Male members are more than 3.
d) To display the name of all female members whose occupation is
‘Business’.

e) To show the occupation of all those members whose income is between


75000 to 110000.

f) To list the details which have an ‘o’ in their name.

g) To arrange the table in the descending order of income.


Q2. Given the following tables for a database Library-

Write commands in SQL for the following-


a) To create the above table.

b) To insert the given data in the above table.

c) To list the names of those students, who have obtained division as first in
the ascending order of name.

\
d) To display a report listing name, subject and annual stipend received
assuming that the stipend column has monthly stipend.

e) To count the number of students, who have either accounts or


informatics as subject.

f) To count the number of students according to the division wise.


Q3. Answer the question based on the table given below-

(a) To list the names all the patients admitted after 15/01/98.

(b) To list the names of female patients who are in ENT department.
(c) To list names of all patients with their date of admission in ascending
order.

(d) To display Patient’s Name, Charges, Age for only female patients.

(e) To list all the details of the patients who are Not in Cardiology or ENT or
Surgery department.
Q4. Answer the following SQL queries-
(a) Write the MySQL command for creating a table “BANK” whose structure
is given below-

(b) In a database there are two tables “ITEM” and “CUSTOMER” as shown
below:

Write the command in SQL queries for the following-


i. To display the details of items whose price is in the range of 40 and 95.
`
ii. To display the Customer Name, City from the table Customer and Item
Name and Price from table Item with their corresponding matching ID.

iii. To increase the price of all the products by 50.

c) In a database School there are two tables Employee and Dept as shown
below:

i. Identify the foreign key in the table Employee.


The foreign key for employee table will be Deptno
ii. What output, will you get when an equi join query is executed to get the
Name from Employee table and corresponding Dname from Dept table?
Q5. Consider the following tables Stationary and Consumer-

Write SQL commands for the statement (i) to (iv).


(i) To display the details of those consumers whose Address is Delhi.

(ii) To display the details of Stationary whose Price is in the range of 8 to 15.
(Both Value included)
(iii) To display the ConsumerName, Address from table Consumer, and
Company and Price from table Stationery, with their corresponding
matching S_ID.

(iv) To increase the Price of all Stationery by 2.


Write output for SQL queries (v) to (viii).
(v) SELECT DISTINCT Address FROM Consumer;

(vi)SELECT COMPANY,MAX(PRICE) AS MAXPRICE,MIN(PRICE) AS


MINPRICE,COUNT(*) AS ITEMCOUNT FROM STATIONARY GROUP BY
COMPANY;

(vii) SELECT [Link], [Link],


[Link] FROM Stationary, Consumer WHERE
Consumer.S_ID=Stationary.ST_ID;

(viii) Select StationeryName, Price*3 From Stationery;

You might also like