0% found this document useful (0 votes)
52 views34 pages

Class 12 CS Practical File

The document contains a series of programming exercises that demonstrate various functions and operations in Python. These include generating series, manipulating lists and dictionaries, reading and writing files, and performing string operations. Each exercise is accompanied by example code, input prompts, and expected output.
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)
52 views34 pages

Class 12 CS Practical File

The document contains a series of programming exercises that demonstrate various functions and operations in Python. These include generating series, manipulating lists and dictionaries, reading and writing files, and performing string operations. Each exercise is accompanied by example code, input prompts, and expected output.
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/ 34

COMPUTER PRACTICAL FILE

1. Write a program that generates a series using a function which takes first and last
values of the series and then generates four terms that are equidistant e.g., if two
numbers passed are 1and 7 then function returns 1 3 5 7.
PROGRAM

def s(x,y):

d=round((y-x)/3,2)

return [x,x+d,x+2*d,y]

x=int(input('enter num1:'))

y=int(input("enter num2:"))

print(s(x,y))

OUTPUT

Enter num1:1

Enter num2:7

[1, 3, 5, 7]

2. Write a function that takes two numbers and returns the number that has minimum
one's digit. Eg. If 491 and 278 are the two numbers then the function returns 491 as
1<8. (1 is the unit digit in 491 and 8 is the unit digit in 278)
PROGRAM

def num(x,y):

if x%10>y%10:

return y

elif x%10<y%10:

return x

else:
return "one's place digit is equal"
x=int(input('enter num1:'))

y=int(input('enter num2:'))

print(num(x,y))

OUTPUT

enter the first number 491

enter the second number 278

491

3. Write a function that takes a sentence as an input parameter where each word in
the sentence is separated by a space. The function should replace each blank with a
hyphen and then return the modified sentence.
PROGRAM

def rep(s):

s=s.replace('','-')

return s

s=input("Enter a sentence:")

print('The modified string is:',rep(s))

OUTPUT

Enter a sentence: Hello how are you

The modified string is: Hello-how-are-you

4. Write a function called remove_duplicates that takes a list and returns a new list
with only the unique elements from the original. They don’t have to be in the same
order.
PROGRAM

def remove_duplicates(l):

l1=list(set((l)))
return l1

l=eval(input('Enter a list:'))

print("The new list is:",remove_duplicates(l))

OUTPUT

Enter a list: [1,2,2,2,3,4,5,4,3,4,5]

The new list is: [1, 2, 3, 4, 5]

5. Write a program to read a list of elements. Input an element, from the user, that has
to be inserted into the list. Also input the position at which it is to be inserted. Write a
user defined function to insert the element at the desired position in the list.

PROGRAM

def linsert(l,e,p):

l.insert(p-1,e)

l=eval(input("enter a list:"))

e=eval(input("enter element to be inserted:"))

p=int(input("postion for insertion:"))

linsert(l,e,p)

print(l)

OUTPUT

enter a list of elements [1,2,3,4,5,6,7,4,2,1]

enter the element to be inserted 10

enter the position of insertion 5

[1, 2, 3, 4, 10,5, 6, 7, 4, 2, 1]

6. Write a function that receives two string arguments and checks whether they are
same length strings (returns True in this case otherwise false).
PROGRAM
def length(a,b):
if (len(a)==len(b)):
return True
else:
return False

a=input("Enter a string: ")


b=input("Enter another string: ")
if(length(a,b)):
print("Same String")
else:
print("Not same")

OUTPUT
Enter a string: Python
Enter another string: Program
Not same

Enter a string: Python


Enter another string: Python
Same String

7. Input a string having some digits. Write a function to return the sum of digits
present in this string.

PROGRAM
def add_int():
s=0
s1=input('Enter the string ')
for i in s1:
if i.isdigit():
s+=int(i)
return s

print("Sum of digits: ",add_int())

OUTPUT

Enter the string KA04JE3261


Sum of digits: 16

8. Write a program that checks for presence of a value inside a dictionary and prints
its key.
PROGRAM
d=eval(input("Enter dict"))
val=eval(input("Enter val"))
for k,v in d.items():
if v==val:
break;
if v==val:
print("Key=",k)
else:
print("not found")

OUTPUT
enter a dictionary {1:'a',2:'b',3:'c'}
enter the value 'a'
the value is present in the dictionary.
the key is 1

9. Consider two dictionaries Emp1 and Emp2 each of which contains the items
Employee code and Employee name. Write function to merge these two dictionaries.

INPUT

def merge():

Emp1=eval(input("enter the first dictionary "))

Emp2=eval(input("enter the second dictionary "))

d3={}

d3.update(Emp1)

d3.update(Emp2)

return d3
print('The merged dictionary is', merge())

OUTPUT

enter the first dictionary {101:'Kevin',102:'Oscar',103:'Angela'}

enter the second dictionary {104:'Jim',105:'Dwight',106:'Stanley',107:'Pam'}

the merged dictionary is {101: 'Kevin', 102: 'Oscar', 103: 'Angela', 104: 'Jim', 105:
'Dwight',

106: 'Stanley', 107: 'Pam'}

10. Write a function to find the highest 2 values in a dictionary.

PROGRAM

def m():

d1=eval(input("enter a dictionary "))

l=list(d1.values())

l.sort()

print(l[-1],l[-2])

print("The highest two values are ",m())

OUTPUT

enter a dictionary {111:'a',222:'b',333:'c',444:'x',555:'d'}

The highest two values are x d

11. Write a program that counts the number of characters up to the first $ in a text
file.

PROGRAM

f=open('readme.txt','w')
f.write('Hari om! we have accounted for 700$ in the carnival stalls, we are in short of
100$.thank you. ')
f.close()
f=open('readme.txt','r')
d=f.read()
cnt=0
for char in d:
if char=='$':
break
else:
cnt=cnt+1
print("The number of characters in the file up to first $ :",cnt)
OUTPUT

The number of characters in the file up to first $ : 34

12. Write a function to search and display the details of all trains, whose destination
is "Delhi", from a binary file "TRAIN.DATA". Assuming the binary file is containing the
objects of the following dictionary type. train={'Tno':_____, 'From':___________, 'To':
___________}.

PROGRAM
import pickle
def add():
f=open("TRAIN.DATA","ab")
train={}
train['Tno']=int(input("Enter train code "))
train['From']=input("Enter starting location ")
train['To']=input("Enter destination ")
pickle.dump(train,f)
f.close()
def search():
f=open("TRAIN.DATA","rb")
try:
while True:
train=pickle.load(f)
if train['To']=='Delhi':
print(train)
except EOFError:
pass
f.close()
def main():
while True:
add()
choice=input("Add more records(y/n)?")
if choice=='n':
break
print('Trains having destination as Delhi are:')
search()
main()
OUTPUT
Enter train code 111
Enter starting location Bangalore
Enter destination Delhi
Add more records(y/n)?y
Enter train code 222
Enter starting location Mumbai
Enter destination Bangalore
Add more records(y/n)?y
Enter train code 333
Enter starting location Mumbai
Enter destination Delhi
Add more records(y/n)?y
Enter train code 444
Enter starting location Bangalore
Enter destination Mumbai
Add more records(y/n)?n
Trains having destination as Delhi are:
{'Tno': 111, 'From': 'Bangalore', 'To': 'Delhi'}
{'Tno': 333, 'From': 'Mumbai', 'To': 'Delhi'}

13. Write a function that reads a csv file and creates another csv file with the same
content, but with a different delimiter.

PROGRAM

import csv

f=open('employee.csv','w',newline='')

emp=csv.writer(f)

emp.writerow(['ID','Name','Salary'])

n=int(input('enter the number of records '))

for i in range(n):

ID=int(input('enter ID of employee '))

name=input('enter the name ' )

salary=float(input("enter the salary "))

emp_rec=[ID,name,salary]

emp.writerow(emp_rec)

f.close()

def copycsv():

fh1=open('employee.csv','r')

d=csv.reader(fh1)
fh=open('copyemp.csv','w',newline='')

l=csv.writer(fh,delimiter='|')

for j in d:

l.writerow(j)

fh.close()

copycsv()

OUTPUT
enter the number of records 3
enter ID of employee 101
enter the name Michael Scott
enter the salary 80000
enter ID of employee 102
enter the name Jim Halpert
enter the salary 70000
enter ID of employee 103
enter the name Kevin Malone
enter the salary 65000

ORIGINAL CSV FILE – employee.csv


ID,Name,Salary
101,Michael Scott,80000.0
102,Jim Halpert,70000.0
103,Kevin Malone,65000.0
NEW CSV FILE WITH SAME CONTENT BUT DIFFERENT DELIMITER -
copyemp.csv

ID|Name|Salary
101|Michael Scott|80000.0
102|Jim Halpert|70000.0
103|Kevin Malone|65000.0

14. Read a text file line by line and display each word separated by a #.

PROGRAM

f=open('test.txt','r')
while (True):

line=f.readline()

if not line:

break

else:

print(line.replace(' ','#'))

f.close()

OUTPUT

Python#is#a#programming#language

Python#is#a#high#level#language

Python#is#an#interpreted#language

15. Read a text file and display the number of vowels/ consonants/ uppercase/
lowercase characters in the file.

PROGRAM

f=open("test.txt","r")
vcount=ccount=ucount=lcount=0
vowels="aeiouAEIOU"
name=f.read()
print(name)
for char in name :
if char in vowels:
vcount=vcount+1
elif 65<=ord(char.upper())<=90:
ccount=ccount+1
if char.isupper():
ucount=ucount+1
elif char.islower():
lcount=lcount+1
print("Number of vowels:",vcount)
print("Number of consonants:",ccount)
print("Number of uppercase characters:",ucount)
print("Number of lowercase characters in:",lcount)
OUTPUT

Number of vowels: 31

Number of consonants: 52

Number of uppercase characters: 3

Number of lowercase characters in: 80

16. Remove all the lines that contain the character 'a' in a file and write it to another
file.

PROGRAM

f=open("test.txt","r")

f1=open("test1.txt","w")

l1=[]

l=f.readlines()

for line in l:

if line.count('a')>0:

f1.write(line)

else:

l1.append(line)

f1.close()

f.close()

f=open("test.txt","w")

f.writelines(l1)

f.close()
OUTPUT

Original File – test.txt

Welcome to New Horizon.

I study in class 12.

New File – test1.txt

I study in class 12.

Modified File - test.txt

Welcome to New Horizon.

17. 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.

PROGRAM

import pickle

f=open('stu.binary','wb')

data={}

n=int(input('enter the number of records '))

for i in range(n):

data['rollno']=int(input('enter roll number '))

data['name']=input('enter the name ')

pickle.dump(data,f)

f.close()

s=int(input('enter the roll number to search for:'))

fh=open('stu.binary','rb')

d=pickle.load(fh)

if d['rollno']==s:

print(data['name'])
else:

print('roll number not found.')

fh.close()

OUTPUT

enter roll number:101

enter the name:angela

enter roll number:102

enter the name:dwight

enter roll number:103

enter the name:jim

enter roll number:104

enter the name:pam

enter roll number:105

enter the name:ryan

enter the roll number to search for:104

pam

18. Create a binary file with roll number, name and marks. Input a roll number and
update the marks.

PROGRAM

import pickle

f=open("binfile","wb")

l=[]

found=0

for i in range(5):
r=int(input("Enter roll"))

n=input("Enter name")

m=int(input("Enter marks"))

l=[r,n,m]

pickle.dump(l,f)

f.close()

f=open("binfile","rb+")

rd=int(input("Enter roll to update"))

try:

while True:

pos=f.tell()

l=pickle.load(f)

if l[0]==rd:

l[2]=int(input("Enter marks"))

f.seek(pos)

pickle.dump(l,f)

found=1

break

except EOFError:

if found==0:

print("No match found")

else:

print("Successfully updated")

print("Student File")

print("============")
f.seek(0)

try:

while True:

r=pickle.load(f)

print(r)

except EOFError:

f.close()

OUTPUT

Enter roll: 1

Enter name: Ram

Enter marks: 70

Enter roll: 2

Enter name: Shyam

Enter marks: 72

Enter roll: 3

Enter name: Hari

Enter marks: 65

Enter roll: 4

Enter name: Kavitha

Enter marks: 80

Enter roll: 5

Enter name: Krishna

Enter marks: 75
Enter roll to update: 4

Enter marks: 95

Student File
============
[1, 'Ram', 70]
[2, 'Shyam', 72]
[3, 'Hari', 65]
[4, 'Kavitha', 95]
[5, 'Krishna', 75]

19. Write a random number generator that generates random numbers between 1
and 6(simulates a dice).

PROGRAM

def roll_dice():

import random

return random.randint(1,6)

print('number generated is',roll_dice())

OUTPUT

number generated is 4

20. Create a CSV file by entering user-id and password, read and search the
password for given user-id.

PROGRAM

import csv

f=open('adm','w')

r=csv.writer(f)

r.writerow(['user ID','password'])
n=int(input('enter the number of records '))

for i in range(n):

username=input('enter user ID ')

password=input('enter password ')

rec=[username,password]

r.writerow(rec)

f.close()

def search():

fh=open('adm','r')

l=csv.reader(fh)

user=input('enter your user ID to get password ')

if user==rec[0]:

print(password)

else:

print('user not found.')

fh.close()

search()

OUTPUT

enter the number of records 3

enter user ID michael123

enter password hollyfax

enter user ID jim_halpert

enter password pamela67

enter user ID pam_2

enter password jimcecephilip


enter your user ID to get password pam_2

jimcecephilip

21.Write a program that depending upon user's choice, either pushes or pops an
element in a stack.

def push(item):

stack.append(item)

def pop():

if stack==[]:

print("There are no elements in the stack.")

return

return stack.pop()

stack=[]

ans='Y'

while ans=='Y'or ans=='y' :

print("\nYou have following options :")

print("\n1. Push an element in the stack. \n2. Pop an element from the stack. ")

choice=int(input("Enter your choice : "))

if choice==1 :

item=int(input("Enter the element to be pushed in the stack : "))

push(item)

print("Stack : ",stack)

elif choice==2 :

item=pop()

if item!=None :
print(item, " is removed from the stack.")

if stack!=[]:

print("Stack : ",stack)

else :

print("Invalid choice.")

ans=input("Do you want to continue(Y/N) : ")

Output:

You have following options :

1. Push an element in the stack.

2. Pop an element from the stack.

Enter your choice : 1

Enter the element to be pushed in the stack : 1

Stack : [1]

Do you want to continue(Y/N) : y

You have following options :

1. Push an element in the stack.

2. Pop an element from the stack.

Enter your choice : 1

Enter the element to be pushed in the stack : 2

Stack : [1, 2]

Do you want to continue(Y/N) : y

You have following options :

1. Push an element in the stack.

2. Pop an element from the stack.

Enter your choice : 1


Enter the element to be pushed in the stack : 3

Stack : [1, 2, 3]

Do you want to continue(Y/N) : y

You have following options :

1. Push an element in the stack.

2. Pop an element from the stack.

Enter your choice : 2

3 is removed from the stack.

Stack : [1, 2

22. A line of text is read from the input terminal into a stack. Write a program to output
the string in the reverse order, each character appearing twice.

def push(line):

for item in line :

stack.append(item)

def pop():

return stack.pop()

line=input("Enter a line of text : ")

stack=[]

push(line)

if stack==[] :

print("Empty string.")

else :

print("\nReversed string : ")

for item in range(len(stack)):


print(pop()*2, end="")

Output:

Enter a line of text : Hello World

Reversed string :

ddllrrooWW oolllleeHH

23. Write PUSH (Books) and POP (Books) methods, in python to add Books and
remove Books considering them to act as Push and Pop operations of stack.

def push(book):

stack.append(book)

def pop():

if stack==[]:

print("There are no books.")

return

return stack.pop()

stack=[]

ans='Y'

while ans=='Y'or ans=='y' :

print("\nYou have following options :")

print("\n1. Add a book. \n2. Remove a book. ")

choice=int(input("Enter your choice : "))

if choice==1 :

book=input("Enter the book to be added : ")

push(book)
print("Books : ",stack)

elif choice==2 :

book=pop()

if book!=None :

print(book, " is removed .")

if stack!=[]:

print("Books : ",stack)

else :

print("Invalid choice.")

ans=input("Do you want to continue(Y/N) : ")

Output:

You have following options :

1. Add a book.

2. Remove a book.

Enter your choice : 1

Enter the book to be added : aaa

Books : ['aaa']

Do you want to continue(Y/N) : y

You have following options :

1. Add a book.

2. Remove a book.

Enter your choice : 2

aaa is removed.

Do you want to continue(Y/N) : y

You have following options :


1. Add a book.

2. Remove a book.

Enter your choice : 2

There are no books.

Do you want to continue(Y/N) : n

Database
24. To create a database class.

CREATE DATABASE class;

25. To create student table with the student id, class, section, gender, name, dob,
and marks as attributes where the student id is the primary key.

CREATE TABLE student (studentid INT PRIMARY KEY,class DECIMAL(2),section


VARCHAR(1),gender VARCHAR(6),studentname VARCHAR(30),dob DATE,marks
DECIMAL(4));

Output:

studentid class section gender studentname dob marks

26. To insert the details of at least 5 students in the above table.

INSERT INTO student VALUES(1,12,”A”,”M”,”Anand”,”2006-06-06",56).

(2,12,”B”,”M”,”Anand”,”2005-04-04",59),

(3,12,”C”,”M”,”Ansuh”,”2005-05-04",49),

(4,12,”A”,”F”,”Anuj”,”2005-04-06",43),

(5,12,”A”,”F”,”Anoop”,”2005-06-06",75);
27. To display the entire content of table.

SELECT * FROM student;

Output:

studentid class section gender studentname dob marks

1 12 A M Anand 2006-06-06 56

2 12 B M Anish 2005-04-04 59

3 12 C M Anush 2005-05-04 49

4 12 A F Anuj 2005-04-06 43

5 12 B F Anoop 2005-06-06 75

28. To display Rno, Name and Marks of those students who scored more than 50.

SELECT studentid,studentname,marks FROM student WHERE marks>50;

Output:

studentid studentname marks

1 Anand 56

2 Anish 59

5 Anoop 75

29. To find the average of marks from the student table.

SELECT AVG(marks) as avgmarks FROM student;

Output:

avgmarks

56.4000
30.To find the number of students, who are from section ‘A’.

SELECT count(*) FROM student WHERE section = 'A';

Output:

count(*)

31.To display the information all the students, whose name starts with ‘AN’
(Examples: ANAND, ANISH,,..)

SELECT * FROM student WHERE studentname LIKE 'An%';

Output:

studentid class section gender studentname dob marks


1 12 A M Anand 2006-06-06 56
2 12 B M Anish 2005-04-04 59
3 12 C M Anush 2005-05-04 49
4 12 A F Anuj 2005-04-06 43
5 12 B F Anoop 2005-06-06 75

32. To display Rno, Name, DOB of those students who are born between ‘2005- 01-
01’ and ‘2005-12-31’.

SELECT studentid,studentname,dob FROM student3 WHERE dob BETWEEN


'2005-01-01' and '2005-12-31';

Output:

studentid studentname dob


2 Anish 2005-04-04
3 Anush 2005-05-04
4 Anuj 2005-04-06
5 Anoop 2005-06-06
33.To display Rno, Name, DOB, Marks, Email of male students in ascending order
of their names.

SELECT studentid,studentname,dob,marks FROM student WHERE gender = 'M'


ORDER BY studentname;

Output:

studentid studentname dob marks


1 Anand 2006-06-06 56
2 Anish 2005-04-04 59
3 Anush 2005-05-04 49

34.To display Rno, Gender, Name, DOB, Marks, Email in descending order of their
marks.

SELECT studentid,gender,studentname,dob,marks FROM student ORDER BY


marks DESC;

Output:

studentid gender studentname dob marks


5 F Anoop 2005-06-06 75
2 M Anish 2005-04-04 59
1 M Anand 2006-06-06 56
3 M Anush 2005-05-04 49
4 F Anuj 2005-04-06 43

35.To display the unique section available in the table.

SELECT DISTINCT(section) FROM student;

Output:

section
A
B
C
36.To display the sum and average marks of boys and girls separately.

SELECT SUM(marks) as summarks,AVG(marks) as avgmarks FROM student


GROUP BY gender;

Output:

gender summarks avgmarks

male 164 54.6667

female 118 59.0000

37.To find the minimum and maximum marks scored by boys and girls.

SELECT MIN(marks) as minmarks,MAX(marks) as maxmarks FROM student group


by gender;

Output:

gender minmarks maxmarks


male 49 59
female 43 75

38.Create a relation 'Competition' to store the details of the students who are
participating in school competitions. The attributes are Stud_id, Comp.

CREATE TABLE Competition (stud_id INT ,Comp VARCHAR(20), FOREIGN KEY


(stud_id) REFERENCES student (studentid));

39.Display the name and class of the students participating in Dance.

SELECT studentname,class from student,competition where comp=’dance’ and


stud_id=studentid
Output:

studentname class
Anand 12
Anuj 12
Anoop 12

40.Write a python program to accept the details of students as input and store it in
student table.

import mysql.connector

db = mysql.connector.connect(

host="localhost",

user="root",

passwd="root",

database="class")

mycursor=db.cursor()

n=int(input("number of students"))

for i in range(n):

sid=int(input("enter student id"))

cl=int(input("enter class"))

sn=input("enter name")

val=(Stud_ID,Class,studentname)

sql="INSERT INTO student (studentid,Class,studentname) VALUES({},{},’{}’)" .

format(sid,cl,sn)

mycursor.execute(sql)

db.commit()

print("inserted")
Input:

number of students3

enter student id1

enter class12

enter nameabc

enter student id2

enter class12

enter namedef

enter student id3

enter class12

enter nameghi

Output:

inserted

41.Write a python program to display the details of the students from student table
based on the user input.

import mysql.connector

db = mysql.connector.connect(

host="localhost",

user="root",

passwd="root",

database="class")

mycursor=db.cursor()
n=int(input("enter student id to find"))

mycursor.execute("SELECT * FROM class.student4 WHERE


studentid={})".format(n))

data=mycursor.fetchone()

print(data)

Input:

enter student id to find2

Output:

(2, Decimal('12'), 'def')

42. Write a python program to delete the record of a student by giving roll no as
input.

import mysql.connector

db = mysql.connector.connect(

host="localhost",

user="root",

passwd="root",

database="class")

mycursor=db.cursor()

n=int(input("enter student id to delete"))

sql="Delete from student where studentid={}".format(n)

mycursor.execute(sql)

db.commit()

print(“Record has been deleted”)


Input:

enter student id to find2

Output:

Record has been deleted

43. Write a python program to update the dob of a student.

import mysql.connector

db = mysql.connector.connect(

host="localhost",

user="root",

passwd="root",

database="class")

mycursor=db.cursor()

n=int(input("enter student id to update"))

db=input(“Enter the correct date of birth”)

sql="update student set dob=’{}’ where studentid={}".format(db,n)

mycursor.execute(sql)

db.commit()

print(“Record has been updated”)

Input:

enter student id to update 1

Enter the correct date of birth 2005-04-01

Output:

Record has been updated

You might also like