0% found this document useful (0 votes)
12 views

PracticalsPrgms12A (1)

The document contains a list of practical Python programming exercises for Class XII A Computer Science. Each exercise includes a description, sample code, and expected output, covering various topics such as calculating averages, counting characters, working with dictionaries, and file handling. The exercises aim to enhance students' programming skills through hands-on practice.

Uploaded by

evanshisaini123
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)
12 views

PracticalsPrgms12A (1)

The document contains a list of practical Python programming exercises for Class XII A Computer Science. Each exercise includes a description, sample code, and expected output, covering various topics such as calculating averages, counting characters, working with dictionaries, and file handling. The exercises aim to enhance students' programming skills through hands-on practice.

Uploaded by

evanshisaini123
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/ 25

Class XII A Computer Science

List of Practical –
1. Write a Python program to take three numbers from user and print their
average.

#Program to find average of three numbers


a = int(input("Enter first number : "))
b = int(input("Enter second number : "))
c = int(input("Enter third number : "))
avg = (a+b+c)/3
print("Average of ", a, b, "and", c, "=", avg)

Output-
Enter first number : 10
Enter second number : 20
Enter third number : 30
Average of 10 20 and 30 = 20.0
2. Write a Python program to read a line and print number of uppercase letters,
number of lowercase letters, number of alphabets and number of digits in it.

# Program to read a line and print number of uppercase letters,


#number of lowercase letters, number of alphabets and number
#of digits
s = input("Enter some text : ")
acount = ucount = lcount = dcount = scount = 0
for i in s:
if i.isalpha():
acount = acount +1
if i.isupper():
ucount = ucount + 1
elif i.islower() :
lcount += 1
elif i.isdigit():
dcount += 1
elif i.isspace():
scount = scount + 1
print("Number of alphabets = ", acount)
print("Number of uppercase letters = ", ucount)
print("Number of lowercase letters = ", lcount)
print("Number of digits = ", dcount)
print("Number of spaces = ", scount)

Output
Enter some text : I Am 15 YearS Old
Number of alphabets = 11
Number of uppercase letters = 5
Number of lowercase letters = 6
Number of digits = 2
Number of spaces = 4
3. Write a Python program to create a dictionary whose keys are months names
and values are number of days in the corresponding months. Ask the user to
enter a month name and use dictionary to print number of days in that
month.

# program to create a dictionary whose keys are months names #and


values are number of day
d = {"jan" : 31, "feb" : 28, "mar" : 31, "apr" : 30, "may" : 31, "jun" : 30,
"jul" : 31, "aug" : 31, "sep" : 30, "oct" : 31, "nov" : 30, "dec" : 31}
mon = input("Enter first three characters of month name : ")
found = False
for a in d:
if mon.lower() == a:
print("Number of days in ", mon, " = ", d[a])
found = True
if found == False:
print("Month not found.")

Output-
Enter first three characters of month name : Mar
Number of days in Mar = 31

4. Given 3 lists L1, L2 and L3, Write a Python program to add individual
elements of L1 and L2 to L3. The order of elements in the resultant list should
be elements of L3, L1 and L2.
#Program to add individual elements of L2 and L3 to L1
L1 = [1, 3, 5, 7]
L2 = [2, 4, 6, 8]
L3 = [10, 20, 30, 40]
print("L1 = ", L1)
print("L2 = ", L2)
print("L3 = ", L3)
L3.extend(L1)
L3.extend(L2)
print("Modified list, L3 = ", L3)
Output –
L1 = [1, 3, 5, 7]
L2 = [2, 4, 6, 8]
L3 = [10, 20, 30, 40]
Modified list, L3 = [10, 20, 30, 40, 1, 3, 5, 7, 2, 4, 6, 8]

5. Write a Python function to check whether a number entered by a user is even


or odd.
#Function to check whether a number entered by a user is even or
#odd.
def evenodd(n):
if n% 2 == 0:
print(n, " is an even number.")
else:
print(n, " is an odd number.")
#Main Program
n = int(input("Enter a number : "))
evenodd(n)

Output-
Enter a number : 25
25 is an odd number.

6. Write a void function in Python to find square of a number.


#Function to find square of a number.
def square(n):
sq = n * n
print("Square of ", n, " = ", sq)
#Main Program
n = int(input("Enter a number : "))
square(n)

Output-
Enter a number : 15
Square of 15 = 225
7. Write a Python program to create a function to print sum of squares of first n
natural numbers.

#Program to print sum of squares of first n natural numbers using function


#Function to find sum of squares of n numbers
def SumSq(n):
s=0
for i in range (1, n+1):
print(i * i, end = ' ')
s = s + (i * i)
return s
#Main program
num = int(input("Enter the number of terms : "))
ans = SumSq(num)
print('\nSum of Squares of first ', num, 'numbers = ',ans)

Output –
Enter the number of terms : 6
1 4 9 16 25 36
Sum of Squares of first 6 numbers = 91

8. Write a python program to read a text file line by line and display each word
separated by #.
#to read a text file line by line and display each word separated by #
f1 = open("D:\\PythonPr\\abc.txt","r")
while True:
ln = f1.readline()
if ln!="":
L=ln.split()
for i in L:
print(i,end="#")
else:
break
f1.close()

Output-
Twinkle#twinkle#little#star#How#I#wonder#what#you#are#Up#above
#the#world#so#high#Like#a#diamond#in#the#sky#
9. Write a python program to read a text file and display the number of vowels
/consonants/ uppercase /lowercase characters in the file.

#To display the number of vowels /consonants/ uppercase


#/lowercase characters in the file
f1 = open("D:\\PythonPr\\abc.txt","r")
s=f1.read()
#print(s)
acount = ucount = lcount = vcount = ccount = 0
for i in s:
if i.isalpha():
acount = acount +1
if i.isupper():
ucount = ucount + 1
elif i.islower() :
lcount += 1
if i.lower() in 'aeiou':
vcount +=1
else:
ccount += 1

print("Number of alphabets = ", acount)


print("Number of uppercase letters = ", ucount)
print("Number of lowercase letters = ", lcount)
print("Number of vowels = ", vcount)
print("Number of consonants = ", ccount)

Output-
Number of alphabets = 85
Number of uppercase letters = 5
Number of lowercase letters = 80
Number of vowels = 32
Number of consonants = 53
10. Write a python program to write all the lines that contain the characters ‘a' in
another file.

#To write all the lines that contain the characters ‘a' in another file.
f1 = open("D:\\PythonPr\\abc.txt","r")
f2 = open("D:\\PythonPr\\xyz.txt","w")
while True:
ln = f1.readline()
if ln != "":
for i in ln:
if i == 'a' or i == 'A':
f2.write(ln)
else:
break
f1.close()
f2.close()

Output-
abc.txt –
Twinkle, twinkle, little star
How I wonder wht you re
Up bove the world so high
Like A dimond in the sky
Xyz.txt-
Twinkle, twinkle, little star
Like A dimond in the sky
11. Write a python program to create a binary file with name and roll number.
Search for a given roll number and display the name. If not found display
appropriate message.

import pickle
f1 = open("D:\\PythonPr\\myfile.dat","wb")
stud = {}
ans = 'y'
while ans == 'y' or ans == 'Y' :
s_roll = int(input("Enter Roll Number : "))
sname = input("Enter Name of Student : ")
marks = float(input("Enter marks : "))
stud["Roll"] = s_roll
stud["Name"] = sname
stud["Marks"] = marks
pickle.dump(stud, f1)
ans = input("Do you want to enter more records? (y/n)")
f1.close()
f2 = open("D:\\PythonPr\\myfile.dat","rb")
stud={}
found = False
print("--------------------------------------------")
print()
n = int(input("Enter the Roll Number to search : "))
try:
while True:
stud = pickle.load(f2)
if stud["Roll"] == n:
print("Record Found")
print("Student Details - ")
print("\tRoll No", stud["Roll"])
print("\tStudent's Name: ", stud["Name"])
print("\tMarks: ", stud["Marks"])
found = True
break
except:
if found == False:
print("Record Not Found")
f2.close()

Output-
Enter Roll Number : 1
Enter Name of Student : Ajay
Enter marks : 65
Do you want to enter more records? (y/n)y
Enter Roll Number : 2
Enter Name of Student : Amar
Enter marks : 87
Do you want to enter more records? (y/n)y
Enter Roll Number : 3
Enter Name of Student : Amit
Enter marks : 45
Do you want to enter more records? (y/n)n
--------------------------------------------

Enter the Roll Number to search : 2


Record Found
Student Details -
Roll No 2
Student's Name: Amar
Marks: 87.0
12. Write a python program to create a binary file with roll number, name and
marks. Input a roll no. And update the marks.
import pickle

f1 = open("D:\\PythonPr\\myfile.dat","wb")
stud = {}
ans = 'y'
while ans == 'y' or ans == 'Y':
s_roll = int(input("Enter Roll Number : "))
sname = input("Enter Name of Student : ")
marks = float(input("Enter marks : "))
stud["Roll"] = s_roll
stud["Name"] = sname
stud["Marks"] = marks
pickle.dump(stud, f1)
ans = input("Do you want to enter more records? (y/n)")
f1.close()
f2 = open("D:\\PythonPr\\myfile.dat","rb+")
stud={}
found = False
print("--------------------------------------------")
print()
n = int(input("Enter the Roll Number to search : "))
try:
while True:
rpos = f2.tell()
stud = pickle.load(f2)
if stud["Roll"] == n:
print("Record Found")
print("Student Details - ")
print("\tRoll No", stud["Roll"])
print("\tStudent's Name: ", stud["Name"])
print("\tMarks: ", stud["Marks"])
marks = float(input("Enter the new marks : "))
stud["Marks"] = marks
f2.seek(rpos)
pickle.dump(stud, f2)
print("Updated Record -")
print("\tRoll No", stud["Roll"])
print("\tStudent's Name: ", stud["Name"])
print("\tMarks: ", stud["Marks"])
found = True
break
except:
if found == False:
print("Record Not Found")
f2.close()

Output -
Enter Roll Number : 1
Enter Name of Student : abc
Enter marks : 34
Do you want to enter more records? (y/n)y
Enter Roll Number : 2
Enter Name of Student : pqr
Enter marks : 45
Do you want to enter more records? (y/n)y
Enter Roll Number : 3
Enter Name of Student : xyz
Enter marks : 67
Do you want to enter more records? (y/n)n
--------------------------------------------

Enter the Roll Number to search : 2


Record Found
Student Details -
Roll No 2
Student's Name: pqr
Marks: 45.0
Enter the new marks : 54
Updated Record -
Roll No 2
Student's Name: pqr
Marks: 54.0
13. Write a python program to create a csv file to store information about a
product – ProductId, PName, Quantity, Price

import csv
f1= open("Product.csv", "w")
rec = []
iwriter = csv.writer(f1)
#Writing header row
iwriter.writerow(['ProductId', 'ProductName', 'Quantity', 'Price'])
ch = 'y'
cnt = 0
while ch == 'y' or ch == 'Y':
print("Enter Product Details : #", cnt + 1)
PId = input("Enter Product Id : ")
PName = input("Enter Product Name : ")
qty = int(input("Enter Quantity : "))
price = float(input("Enter Price : "))
Pr_rec = [PId, PName, qty, price]
rec.append(Pr_rec)
cnt += 1
print("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-")
ch = input("Do you want to enter more records ? (y/n)")
iwriter.writerows(rec)
f1.close()
print("Record saved in csv file.")
Output -
Enter Product Details : # 1
Enter Product Id : P101
Enter Product Name : GelPen
Enter Quantity : 5
Enter Price : 30
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
Do you want to enter more records ? (y/n)y
Enter Product Details : # 2
Enter Product Id : P102
Enter Product Name : Notebook
Enter Quantity : 3
Enter Price : 60
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
Do you want to enter more records ? (y/n)y
Enter Product Details : # 3
Enter Product Id : P103
Enter Product Name : Eraser
Enter Quantity : 6
Enter Price : 10
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
Do you want to enter more records ? (y/n)n
Record saved in csv file.

Product.csv -
ProductId,ProductName,Quantity,Price
P101,GelPen,5,30.0
P102,Notebook,3,60.0
P103,Eraser,6,10.0
14. Write a Python program to read data from a csv file(Product.csv) and display
them.
import csv
with open("Product.csv", "r", newline = "\r\n") as f1:
creader = csv.reader(f1)
for rec in creader:
if rec[0] != "ProductId":
print("Product Id - ", rec[0])
print("Product Name - ", rec[1])
print("Quantity - ", rec[2])
print("Price - ", rec[3])
print("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-")

Output -
Product Id - P101
Product Name - GelPen
Quantity - 5
Price - 30.0
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
Product Id - P102
Product Name - Notebook
Quantity - 3
Price - 60.0
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
Product Id - P103
Product Name - Eraser
Quantity - 6
Price - 10.0
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
15. Write a random number generator that generates random numbers between
1 and 6.
import random
n = random.randrange(1,7)
print("Guess the number on the dice ....(between 1 and 6):")
guess = int(input("Enter a number: "))
while n!= guess:
if guess > 6:
print("Invalid number!!!")
guess = int(input("Enter number again: "))
if guess < n:
print("Too low")
guess = int(input("Enter number again: "))
elif guess > n:
print("Too high!")
guess = int(input("Enter number again: "))
else:
break
print("You guessed it right!!!")

Output-
Guess the number on the dice ....(between 1 and 6):
Enter a number: 4
Too high!
Enter number again: 1
Too low
Enter number again: 2
You guessed it right!!!
16. Write a python program to implement a stack (stack of students name) using
list.
#Function to display elements of stack
def display(st):
if(isEmpty(st)):
print('Stack is empty!!!')
else:
print("Elements of the Stack are :")
for x in range(len(st)-1,-1,-1):
print('\t\t',st[x])

#Function to check if the stack is empty


def isEmpty(st):
if st == []:
return True
else:
return False

#Function to push an element in stack


def push(st, e):
st.append(e)
top = len(st) - 1

#Function to pop/delete an element from the stack


def pop(st):
if(isEmpty(st)):
print('Stack is empty!!!')
else:
e=st.pop()
if len(st) == 0:
top = None
else:
top = len(st) - 1
print('Popped value = ', e)
#Function to display top element of stack
def peek(st):
if(isEmpty(st)):
print('Stack is empty!!!')
else:
top = len(st) - 1
print("Top element of stack is = ", st[top])

# Program starts
st = []
top = None
print("Stack Operations")
print("************")
print("1. Push")
print("2. Pop")
print("3. Peek")
print("4. Display Stack")
print("5. Exit")
while True:
choice=input("Enter your choice...")
if choice=='1':
val = int(input("Enter an element : "))
push(st, val)
elif choice=='2':
pop(st)
elif choice=='3':
peek(st)
elif choice=='4':
display(st)
elif choice == '5':
print('Thankyou...')
break
else:
print("Invalid choice!!!")
Output-
Stack Operations
************
1. Push
2. Pop
3. Peek
4. Display Stack
5. Exit
Enter your choice...1
Enter an element : 12
Enter your choice...1
Enter an element : 14
Enter your choice...1
Enter an element : 16
Enter your choice...4
Elements of the Stack are :
16
14
12
Enter your choice...3
Top element of stack is = 16
Enter your choice...2
Popped value = 16
Enter your choice...4
Elements of the Stack are :
14
12
Enter your choice...2
Popped value = 14
Enter your choice...4
Elements of the Stack are :
12
Enter your choice...3
Top element of stack is = 12
Enter your choice...5
Thankyou...
17. Write a python program to integrate SQL with python and extract and print data
from the table student.(columns – roll int, sname char(20), class int, marks decimal )
import mysql.connector as sq
mycon = sq.connect(host='localhost', user='root', passwd = 'root', database =
'stud')
if mycon.is_connected() == False:
print("Error connecting to MySQL Database")
cur = mycon.cursor()
st = "Select * from student;"
cur.execute(st)
data = cur.fetchall()
print('Student\'s Records : \n')
for i in data:
print('Roll No : ', i[0])
print('Student\'s Name : ', i[1])
print('Class : ', i[2])
print('Marks : ', i[3])
print('_________________________')
mycon.close()

Output-
Student's Records :

Roll No : 101
Student's Name : Amar
Class : 12
Marks : 77.00
_________________________
Roll No : 102
Student's Name : Riya
Class : 12
Marks : 82.00
_________________________
Roll No : 103
Student's Name : Sima
Class : 11
Marks : 66.00
_________________________
18. Write a python program to insert a record in MySQL table stud using database
connectivity.

import mysql.connector as sq
mycon = sq.connect(host='localhost', user='root', passwd = 'root', database =
'stud')
if mycon.is_connected() == False:
print("Error connecting to MySQL Database")
cur = mycon.cursor()
roll = int(input("Enter Roll No. : "))
nm = input("Enter Name : ")
cls = int(input("Enter class : "))
mk = float(input("Enter marks : "))
st = "insert into student values(%s, '%s', %s, %s);"%(roll, nm, cls, mk)
cur.execute(st)
print('Student\'s Records entered successfully.')
mycon.commit()
mycon.close()

Output-
Enter Roll No. : 104
Enter Name : Ajay
Enter class : 11
Enter marks : 69
Student's Records entered successfully.

Database-
19. Write a python program to integrate SQL with python and search a
student using rollno, if it is present, display the record.
import mysql.connector as sq
mycon = sq.connect(host='localhost', user='root', passwd = 'root', database =
'stud')
if mycon.is_connected() == False:
print("Error connecting to MySQL Database")
roll = int(input("Enter roll number to search : "))
cur = mycon.cursor()
st = "Select * from student where roll = {};".format(roll)
cur.execute(st)
data = cur.fetchone()
print('Student\'s Records : \n')
print('Roll No : ', data[0])
print('Student\'s Name : ', data[1])
print('Class : ', data[2])
print('Marks : ', data[3])
mycon.close()

Output –
Enter roll number to search : 102
Student's Records :

Roll No : 102
Student's Name : Riya
Class : 12
Marks : 82.00
20. Write a python database connectivity script that deletes records from emp table
of employee database.
import mysql.connector as sq
mycon = sq.connect(host='localhost', user='root', passwd = 'root', database =
'stud')
if mycon.is_connected() == False:
print("Error connecting to MySQL Database")
roll = int(input("Enter roll number to delete : "))
cur = mycon.cursor()
st = "Delete from student where roll = {};".format(roll)
cur.execute(st)
print('Record deleted successfully.')
mycon.commit()
mycon.close()

Output –
Enter roll number to delete : 103
Record deleted successfully.

Database –
SQL-
1. Write a SQL query to create a table student with following specifications-
Fied name data-type size constraint
S_Roll integer -- Primary key, Not Null
S_Name char 20 Not null
Class integer -- --
Marks decimal -- --

CREATE TABLE student


( S_Roll INT PRIMARY KEY,
S_Name CHAR(30),
Class INT,
Marks DECIMAL (5,2) ) ;

2. Write a SQL query to view structure of above table stud.

DESC student;

3. Insert two records in above table stud.

INSERT INTO student( S_Roll, S_Name, Class, Marks)


VALUES (101, ‘Seema’, 12, 78) ;

INSERT INTO student


VALUES ( 102, ‘Rekha’, 11, 82) ;

4. Display all the records of table stud.

SELECT * FROM student ;

5. Display Name and class of the students whose name starts with letter ‘A'.
SELECT S_Name, Class FROM student
WHERE S_Name LIKE ‘A%’ ;
Consider following table emp and dept
Table - emp
ename empno age deptno salary gender
Nitin 101 42 20 22000 M
Saransh 103 36 30 28000 M
Kavita 107 41 20 35000 F
Aparna 108 34 30 38000 F
Aman 112 31 10 31000 M

Table – dept
deptno department
10 Sales
20 Production
30 IT
40 HR

6. Display name, age, department, salary of all male employees

SELECT ename, age, department, salary


FROM emp, dept
WHERE emp.deptno = dept.deptno
AND gender = ‘M’;

7. Display record of male employees whose salary is more than 25000.


SELECT * FROM emp
WHERE salary > 25000 AND gender = ‘M’ ;

8. Display name, age, deptno, department, salary, gender of employees whose


age is between 32 and 36.
SELECT ename, age, e.deptno, department, salary, gender
FROM emp e, dept d
WHERE e.deptno = d.deptno
AND age BETWEEN 32 AND 36 ;
9. Display total number of all the employees of department number 30.

SELECT count(empno) FROM emp


GROUP BY deptno
HAVING deptno = 30;

10. Display name, department and age of all the female employees of Sales
department in descending order of their age.

SELECT ename, department, age FROM emp, dept


WEHRE e.deptno = d.deptno
AND department = ‘Sales’ AND gender = ‘F’;

You might also like