Computer Science(083)
Practical File
NAME: SUKARN CHOWDHRY
CLASS: XII-S2
BOARD ROLL NO:
1|Page
User Defined Functions
Q: Create a dictionary containing names of competition winner
students as keys and number of their wins as values.
Ans:
d={}
n=int(input("ENTER A NUMBER"))
for i in range(n):
key=input("ENTER THE NAME OF STUDENT")
value=int(input("ENTER THE NO. OF WINS"))
d[key]=value
print(d)
Output:
Q: Write a program that receives two numbers in a function and
returns the results of all arithmetic operation on these numbers.
Ans:
def calc(a,b):
add=a+b
2|Page
sub=a-b
mul=a*b
div=a/b
return add, sub, mul, div
a=int(input("ENTER NUMBER"))
b=int(input("ENTER ANOTHER NUMBER"))
result=calc(a,b)
print("THE RESULT OBTAINED ARE:")
for i in result:
print(i)
Output:
Q: Write a function to swap the values of two variables through a
function.
Ans:
def swap(a,b):
(a,b)=(b,a)
return swap
a=int(input("ENTER a:"))
b=int(input("ENTER b:"))
print("Value of a after swapping is:",b)
3|Page
print("Value of b after swapping is:",a)
Output:
Q: Write a random number generator that generates random
numbers between 1 and 6.
Ans:
import random
a=int(input("ENTER STARTING NUMBER"))
b=int(input("ENTER LAST NUMBER"))
print(random.randint(a,b))
Output:
Q: Write a recursive code to compute the nth Fibonacci number.
Ans:
4|Page
def recur_fibo(n):
if n<=1:
return n
else:
return(recur_fibo(n-1)+recur_fibo(n-2))
n=int(input("ENTER HOW MANY NUMBERS IN THE SERIES:"))
print("THE FIBONACCI SERIES GENERATED:")
for i in range(n):
print(recur_fibo(i))
Output:
Q: Write a Recursive function to calculate the Factorial of a number.
Ans:
def recur_factorial(n):
if n==1:
return n
5|Page
else:
return n*recur_factorial(n-1)
n=int(input("ENTER NUMBER"))
if n<0:
print("PLEASE ENTER A POSITIVE NUMBER")
elif n==0:
print("THE FACTORIAL OF 0 IS 0")
else:
print("THE FACTORIAL OF",n,"IS",recur_factorial(n))
Output:
Q: Write a recursive code to find the sum of all elements in the list.
Ans:
def list_sum(lst):
l=len(lst)
sum=0
for i in lst:
sum += i
return sum
6|Page
lst=eval(input("ENTER LIST:"))
print("THE SUM IS",sum(lst))
Output:
Q: Write a recursive code to implement power function
Ans:
def power(x,n):
if (n==0):
return 1
else:
return x*power(x,n-1)
a=int(input("ENTER NUMBER"))
b=int(input("ENTER THE POWER"))
print(power(a,b))
Output:
7|Page
Q: Write a recursive code to check whether a string is palindrome or
not.
Ans:
def main():
istr=input("ENTER A STRING")
if Palindrome(istr):
print("THE STRING IS PALINDROME")
else:
print("THE STRING IS NOT A PALINDROME")
def Palindrome(string):
if len(string)<=1:
return True
if string[0]==string[len(string)-1]:
return Palindrome(string[1:len(string)-1])
else:
return False
main()
Output:
Q: Write a program to implement a stack using list-like data structure.
8|Page
Ans:
s=[]
ch="y"
while (ch=="y"):
print("1.PUSH")
print("2.POP")
print("3.DISPLAY")
choice=int(input("ENTER CHOICE:"))
if (choice==1):
a=input("ENTER A CHARACTER:")
s.append(a)
elif (choice==2):
if (s==[]):
print("EMPTY STACK")
else:
print("DELETED ELEMENT IS:",s.pop())
elif (choice==3):
l=len(s)
for i in range(l-1,-1,-1):
print(s[i])
else:
print("WRONG OUTPUT:")
c=input("DO YOU WANT MORE(y/n)")
Output:
9|Page
Q: Write a program to implement a queue using list-like data
structure.
Ans:
s=[]
ch="y"
while (ch=="y"):
print("1.INSERT")
print("2.DELETE")
print("3.DISPLAY")
choice=int(input("ENTER YOUR CHOICE:"))
if (choice==1):
a=input("ENTER ANY CHARACTER:")
s.append(a)
10 | P a g e
elif (choice==2):
if (s==[]):
print("EMPTY QUEUE")
else:
print("THE DELETED ELEMENT IS",s.pop())
elif(choice==3):
l=len(s)
for i in range(0,l):
print(s[i])
else:
print("WRONG INPUT")
ch=input("DO YOU WANT MORE(y/n)")
Output:
11 | P a g e
Q: Write a file which reads the file line by line.
Ans:
f=open("story.txt","r")
lines=f.readlines()
for line in lines:
print(line, end=' ')
f.close()
Output:
Q: Write a program to find the size and no of lines in a file.
12 | P a g e
Ans:
f=open("story.txt","r")
lines=f.readlines()
count=0
for i in lines:
count+=1
print("THERE ARE",count,"LINES")
import os
def filesize(filename):
return os.stat(filename),st_size
filename="story.txt"
fsize=os.path.getsize(filename)
print("THE SIZE OF FILE IS",fsize,"BYTES")
Output:
Q: Write a program that displays all the lines that start with letter “A”
in a file and write it into other file.
Ans:
def letterA():
file=open("story 2.txt","r")
line=file.readline()
while line:
13 | P a g e
if line[0]=="A":
print(line)
line=file.readline()
file.close()
y=open("copy.txt","w")
y.write(data)
y.close()'''
Output:
14 | P a g e
BAR GRAPH AND PIE CHART
Q: Write a python program to plot a pie chart for the popular
programming language among the students.
Ans:
import matplotlib.pyplot as plt
labels=["PYTHON","C++","RUBY","JAVA"]
students=[52,30,35,40]
colors=["BLUE","GREEN","LIGHTCORAL","RED"]
explode=(0.3,0,0,0)
plt.pie(students, explode=explode, labels=labels, colors=colors)
plt.title("PROGRAMMING LANGUAGES")
plt.show()
Output:
Q: Write a python program implementing a single list using a
horizontal bar chart.
15 | P a g e
Ans:
import matplotlib.pyplot as plt
y_axis=[20,30,15,40]
x_axis=range(len(y_axis))
plt.barh(x_axis,y_axis,color="black")
plt.show()
Output:
Q: Plot a line chart to depict a comparison of population between
India and Pakistan.
Ans:
import matplotlib.pyplot as plt
year=[1960,1970,1980,1990,2000,2010]
pak=[44,58,78,107,138,170]
ind=[450,554,697,870,1000,1310]
plt.plot(year,pak,color='green')
16 | P a g e
plt.plot(year,ind,color='orange')
plt.xlabel('YEARS')
plt.ylabel('POPULATION IN MILLIONS')
plt.title('INDIA V/S PAKISTAN POPULATION TILL 2010')
plt.show()
Output:
17 | P a g e
MYSQL
Q: Create a table student with 10 dummy records and find the min,
max, sum and average of the marks from this table.
Ans:
CREATION OF TABLE:
mysql> create table student
-> (S_ID INT(2) PRIMARY KEY NOT NULL,
-> NAME CHAR(20),
-> GENDER CHAR(1),
-> MARKS INT (2));
FINAL TABLE:
MAX, MIN, AVERAGE AND SUM OF MARKS:
FOR MAX MARKS
mysql> select max(marks) from student;
FOR MIN MARKS
18 | P a g e
mysql>select min(marks) from student;
For Average Marks
mysql> select avr(marks) from student;
For SUM
mysql>select sum(marks) from student;
19 | P a g e
Q: Write a SQL Query to order the student table in descending order
of marks.
Ans:
mysql> select * from student
->order by marks desc;
20 | P a g e
Q: In the table student write a queries for the respective
requirements
1. Show the name of students in Science stream
mysql> select name from student
-> where stream="science";
Output
21 | P a g e
2. Show the details of students whose marks are between 50 and
60.
mysql> select * from student
-> where marks>=50 and marks<=60;
3. Show the details of students in ascending order of marks
mysql> select * from student
-> order by marks;
4. Write a command to view the structure of table.
22 | P a g e
mysql>desc student;
5. Write a command to change the stream of student to
Humanities whose name is Payal.
mysql> update student
-> set stream="HUMANITIES"
-> where name="PAYAL";
6. Write a command to display the details of students grouped by
stream
mysql> select * from student
-> group by stream;
7. Write a command to count the no of students in humanities
stream.
mysql> select count(stream)
-> from student
-> where stream="HUMANITIES";
8. Write a command to group the stream toppers
select name,stream from student
-> group by stream
23 | P a g e
-> having max(marks);
9. Write a name to delete the record of student whose name is
DEEP SINGH.
mysql> delete from student
-> where name=”DEEP_SINGH”;
10. Write a command to drop the table student
mysql> drop table student;
Q: Write a python program to perform all operation on a table
through menu driven program.
Ans:
def menu():
c="y"
while (c=='y'):
print("1.ADD RECORD")
print("2.UPDATE RECORD")
print("3.DELETE RECORD")
print("4.DISPLAY RECORD")
print("5.EXIT")
choice=int(input("ENTER CHOICE"))
24 | P a g e
if (choice==1):
adddata()
elif(choice==2):
updatedata()
elif (choice==3):
deldata()
elif(choice==4):
fetchdata()
elif(choice==5):
print("EXITING")
break
else:
print("WRONG INPUT")
c=input("DO YOU WANT TO CONTINUE (Y/N)")
def fetchdata():
import mysql.connector
try:
db=mysql.connector.connect(host='localhost',user='root',passwd='sqlcs27',database='test')
cursor=db.cursor()
cursor.execute("SELECT * FROM STUDENT")
result=cursor.fetchall()
for x in result:
print(x)
25 | P a g e
except:
print("ERROR: UNABLE TO FETCH DATA")
def adddata():
import mysql.connector
db=mysql.connector.connect(host='localhost',user='root',passwd='sqlcs27',database='test')
cursor=db.cursor()
cursor.execute("INSERT INTO student VALUES(11,'ANKUSH','M',67)")
cursor.execute("INSERT INTO student VALUES(12,'RITU','F',73)")
db.commit()
print("RECORDS ADDED")
def updatedata():
import mysql.connector
try:
db=mysql.connector.connect(host='localhost',user='root',passwd='sqlcs27',database='test')
cursor=db.cursor()
s=("UPDATE STUDENT set marks=50 where name='ANKUSH'")
cursor.execute(s)
print("RECORD UPDATED")
db.commit()
except Exception as e:
print(e)
def deldata():
import mysql.connector
26 | P a g e
db=mysql.connector.connect(host="localhost",user="root",passwd="sqlcs27",database="test")
cursor=db.cursor()
s=("DELETE FROM STUDENT WHERE NAME='PAYAL'")
cursor.execute(s)
print("RECORD DELETED")
db.commit()
menu()
OUTPUT:
27 | P a g e
(RECORD OF PAYAL DELETED)
28 | P a g e
DJANGO
Q: Create a django application showing the use of POST METHOD.
Ans:
<html>
<head><title>use of port</title></head>
<body>
<center><H2>use of post method</H2>
<form method="GET"action="\getdata\">
<table>
<tr><td>ENTER YOUR NAME</td><td><input type="text"name="name"/></td></tr>
<tr><td>ENTER VALUE1:</td><td><input type="text"name="v1"/></td></tr>
<tr><td>ENTER VALUE2:</td><td><input type="text"name="v2/"></td></tr>
<tr><td><button>SUBMIT FORM</button></td></tr>
</table></form>
</center>
</body>
</html>
OUTPUT:
29 | P a g e
Q: Create a django application showing the use of GET METHOD.
Ans:
<html>
<head>
<title>Home Page</title>
</head>
<body>
<center><H1>GET METHOD</h1></center>
<center><p>Welcome to the <font color=red>First Page</font> in HTML</p></center>
<center><table border=2, bgcolor=yellow>
<tr><th>Roll</th><th>Name</th><th>Age</th></tr>
<tr><td>1</td><td>NAVEEN</td><td>26</td></tr>
<tr><td>2</td><td>ROHIT</td><td>33</td></tr>
</table>
<center><p><H1>THANK YOU</H1></center>
30 | P a g e
</body>
</html>
OUTPUT:
Q: Write a python program to store and display multiple integers in
and form a binary file.
Ans:
def binfile():
import pickle
file=open('data.txt','wb')
while True:
x=int(input("ENTER INTEGER:"))
pickle.dump(x,file)
ans=input("DO YOU WANT TO ENTER MORE DATA (Y/N)")
31 | P a g e
if ans.upper()=='N':
break
file.close()
file=open('data.txt','rb')
try:
while True:
y=pickle.load(file)
print(y)
except EOFError:
pass
file.close()
binfile()
OUTPUT:
32 | P a g e