Uploaded by Shagiffta Parvin

4sam

advertisement
SARVODAYA KANYA VIDYALAYA ,
KHAJOORI KHAS
COMPUTER SCIENCE (083)
PRACTICAL FILE
2022-2023
SUBMITTED BY: Sameera
CLASS AND SECTION : XII ‘C’
ROLL NUMBER: 15
INDEX
S.NO PROGRAM
PAGE
NO.
1a.
Write a program in python to enter two numbers and print the
arithmetic operation like +,-,*,/,//,% and **.
5
1b.
Write a program in python to enter two numbers and print the
arithmetic operation like +,-,*,/,//,% and ** using functions.
6,7,8
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
Write a program in python to find the factorial of a number using
function.
Write a program in python to enter the number of terms and to
print the Fibonacci series.
Write a Program in python to accept a string and to check whether
it is a palindrome or not.
Write a program in python to display those string which starts with
“A” from a given list.
Write a program in python to read a file line by line and print it.
Write a program in python to read a file line by line and display
each word separated by a #.
Write a program in python to read a text file and display the
number of vowels/Consonants/ uppercase and lowercase
characters in the file.
Write a program in python to remove all the lines that contain the
character ‘a’ in a file and write it to another file.
Write a program in python to find the occurrence of a given
word/string in the file.
Write a program in python to create a binary file with name and
roll no. Search for a given roll number and display the name if not
found display appropriate message.
Write a program in python to create a binary file with name and
roll no. and marks. Input a roll number and update the marks if roll
no not found display appropriate message.
Write a program in python to create a CSV file with details of 5
students.
Write a program in python to read a CSV file and print data.
Write a random number generator that generates random number
between 1 and 6(simulate a dice)
Write a menu based program to perform the operation on stack in
python
Write a menu based program to Maintaining Book details like
bcode, btitle and price using stacks in python.
Write a menu based program to add, delete and display the
record of hostel using list as stack data structure in python. Record
of hostel contains the fields : Hostel number,Total Students and
Total Rooms.
Mysql queries set-1
9,10
11
12
13
14
15
16,17
18
19
20,21
22,23
24
25
26
28,29
30,31,32
33,34,35
37,38,39
TEACHER’S
SIGN
20.
Mysql queries set-2
40,41
21.
Mysql queries set-3
4247
22.
Mysql queries set-4
4850
23.
Mysql queries set-5
24.
Write program in python using mysql python connectivity to create
table student, insert data into student table and display record.
51,52
25.
Write a program using mysql python connectivity to search the record
of a student using ID from student table.
53
26.
27.
Write a program using python mysql connectivity to update subject of
a student.
Write a program using python mysql connectivity to delete a record
from student table.
1a.WAP in python to enter two numbers and print the arithmetic operation
like +,-,*,/,//,% and**.
Code:
num1=int(input("Enter the first number : "))
num2=int(input("Enter the Second number : "))
print("The addition of numbers is = ",num1+num2)
print("The subtraction of numbers is = ",num1-num2)
print("The multiplication of numbers is = ",num1*num2)
print("The division of numbers is = ",num1/num2)
print("The floor division of numbers is = ",num1//num2)
print("The remainder of number is = ",num1%num2)
output:
1b. Write a program in python to enter two numbers and print the
arithmetic operation like +,-,*,/,//,% and ** using functions.
Code:
def add(a,b):
res=a+b
return res
def sub(a,b):
res=a-b
return res
defmul(a,b):
res=a*b
return res
def div(a,b):
res=a/b
return res
deffdiv(a,b):
res=a//b
return res
def rem(a,b):
res=a%b
return res
def power(a,b):
res=a**b
return res
num1=int(input("Enter the first number : "))
num2=int(input("Enter the Second number : "))
print("The addition of numbers is = ",add(num1,num2))
print("The subtraction of numbers is = ",sub(num1,num2))
print("The multiplication of numbers is = ",mul(num1,num2))
print("The division of numbers is = ",div(num1,num2))
print("The floor division of numbers is = ",fdiv(num1,num2))
print("The remainder of number is = ",rem(num1,num2))
print("The Exponent of number is = ",power(num1,num2))
Output:
2. Write a program in python to find the factorial of a number using
function.
CODE:
def fact(n):
f=1
while(n>0):
f=f*n
n=n-1
return f
n=int(input("Enter a number to find the factorial : "))
if(n<0):
print("Factorial of negative number is not possible")
elif(n==0):
print("Factorial of zero is 1")
else:
print("Factorial of ",n,"is ",fact(n))
OUTPUT:
3. Write a program in python to enter the number of terms and to print the
Fibonacci series.
CODE:
def fibonacci(n):
n1,n2=0,1
nterms=int(input("Enter the numbers of terms to print fibbonaci series : "))
if nterms<=0:
print("Please enter a positive value ")
else:
print(nterms," terms of Fibonacci series : ")
fibonacci(nterms)
count=0
while(count<nterms):
print(n1)
nth=n1+n2
n1=n2
n2=nth
count=count+1
OUTPUT:
4. Write a Program in python to accept a string and to check whether it is a
palindrome or not.
CODE:
str=input("Enter the string : ")
l=len(str)
p=l-1
index=0
while(index<p):
if(str[index]==str[p]):
index=index+1
p=p-1
else:
print("String is not a palindrome")
break
else:
print("String is palindrome")
OUTPUT:
5. Write a program in python to display those string which starts with “A”
from a given list.
CODE:
L=['RAM','ALISHA','append','Truth']
count=0
fori in L:
ifi[0] in ('a','A'):
count=count+1
print(i)
print("String starting with A appearing",count,"times.")
OUTPUT:
6.Write a program in python to read a file line by line and print it.
CODE:
f1=open("seven.txt","r")
count=0
for i in f1.readlines():
count+=1
print("Line",count,":",i)
OUTPUT:
7. Write a program in python to read a file line by line and display each
word separated by a #.
CODE:
f1=open("seven.txt","r")
fori in f1.readlines():
words=i.split()
for w in words:
print(w+"#",end='')
print()
f1.close()
OUTPUT:
8.Write a program in python to read a text file and display the number of
vowels/Consonants/ uppercase and lowercase characters in the file.
CODE:
f1=open("seven.txt","r")
vowels=0
consonants=0
uppercase=0
lowercase=0
v=['A','a','E','e','I','i','O','o','U','u']
str=f1.read()
print(str)
fori in str:
ifi.islower():
lowercase+=1
elifi.isupper():
uppercase+=1
for j in str:
if j in v:
vowels+=1
else:
ifj.isalpha():
consonants+=1
print("Lower case : ",lowercase)
print("Upper case : ",uppercase)
print("vowels : ",vowels)
print("consonants : ",consonants)
OUTPUT:
9. Write a program in python to remove all the lines that contain the
character ‘a’ in a file and write it to another file.
CODE:
file1=open('seven.txt')
file2=open('myfilenew.txt','w')
for line in file1:
if "a" not in line:
file2.write(line)
print("File copied sucessfully")
file1.close()
file2.close()
OUTPUT:
10.Write a program in python to find the occurrence of a given word/string
in the file.
CODE:
f1=open('seven.txt','r')
data=f1.read()
a=data.split()
str1=input("Enter the word to search : ")
count=0
for word in a:
if word==str1:
count=count+1
if count==0:
print("word not found")
else:
print("Word occurs ",count," times")
OUTPUT:
11.Write a program in python to create a binary file with name and roll no.
Search for a given roll number and display the name if not found display
appropriate message.
CODE:
import pickle
S=[]
f=open("stud.dat","wb")
c='y'
while c=='y' or c=='Y':
rno=int(input("Enter the roll no. of the student : "))
name=input("Enter the name of the student : ")
S.append([rno,name])
pickle.dump(S,f)
c=input("Do you want to add more?")
f.close()
f=open('stud.dat','rb')
student=[]
try:
while True:
student=pickle.load(f)
exceptEOFError:
f.close()
found=False
rno=int(input("Enter the roll no. of the student to be search: "))
for a in student:
if a[0]==rno:
print("Name is : ",a[1])
found=True
if found==False:
print("Student not found")
OUTPUT:
12.Write a program in python to create a binary file with name and roll no.
and marks. Input a roll number and update the marks if roll no not found
display appropriate message.
CODE:
import pickle
S=[]
f=open("stud1.dat","wb")
c='y'
while c=='y' or c=='Y':
rno=int(input("Enter the roll no. of the student : "))
name=input("Enter the name of the student : ")
marks=int(input("Enter the marks : "))
S.append([rno,name,marks])
pickle.dump(S,f)
c=input("Do you want to add more?")
f.close()
f=open('stud1.dat','rb')
student=[]
try:
while True:
student=pickle.load(f)
exceptEOFError:
f.close()
found=False
rno=int(input("Enter the roll no. of the student for updating marks: "))
for a in student:
if a[0]==rno:
print("Name is : ",a[1])
print("Current marks : ",a[2])
m=int(input("Enter new marks : "))
a[2]=m
print("Record Updated")
found=True
if found==False:
print("Roll no. not found")
OUTPUT:
13. Write a program in python to create a CSV file with details of 5
students.
CODE:
import csv
f=open("student.csv","w",newline="")
cw=csv.writer(f)
cw.writerow(['Rollno','Name','Marks'])
fori in range(5):
print("Student ",i+1," record : ")
rollno=int(input("Enter Roll No : "))
name=input("Enter name : ")
marks=float(input("Enter Marks : "))
sr=[rollno,name,marks]
cw.writerow(sr)
f.close()
print("File created successfully")
OUTPUT:
14. Write a program in python to read a CSV file and print data.
CODE:
import csv
f=open("student.csv","r")
cr=csv.reader(f)
print("Content of CSV file : ")
for data in cr:
print(data)
f.close()
OUTPUT:
15.Write a random number generator that generates random number
between 1 and 6(simulate a dice)
import random
while True:
choice=input("Enter 'r' for rolling the dice or press any key to quit ")
if (choice.lower()!='r'):
break
n=random.randint(1,6)
print(n)
OUTPUT:
16. Write a menu based program to perform the operation on stack in
python.
Source Code:stack = [ ]
while True :
print()
print("Enter your choice as per given -")
print("1 = For insert data Enter insert ")
print("2 = For delete data enter delete ")
print("3 = For Exit enter exit ")
print()
user = input("Enter your choice :- ")
if user == "insert" :
data = input("Enter the name of student :- ")
stack.append(data)
elif user == "delete" :
if stack == [ ]:
print("UnderFlow")
else :
stack.pop()
else :
break
print("Now our stack = ",stack)
17. Write a menu based program to Maintaining Book details like bcode,
btitle and price using stacks in python.
Source Code:book=[]
def push():
bcode=input("Enter bcode:- ")
btitle=input("Enter btitle:- ")
price=input("Enter price:- ")
bk=(bcode,btitle,price)
book.append(bk)
def pop():
if(book==[]):
print("Underflow / Book Stack in empty")
else:
bcode,btitle,price=book.pop()
print("poped element is ")
print("bcode:- ",bcode," btitle:- ",btitle," price:- ",price)
def traverse():
if not (book==[]):
n=len(book)
for i in range(n-1,-1,-1):
print(book[i])
else:
print("Empty , No book to display")
while True:
print("Book Stall")
print("*"*40)
print("1. Push")
print("2. Pop")
print("3. Traversal")
print("4. Exit")
ch=int(input("Enter your choice:- "))
if(ch==1):
push()
elif(ch==2):
pop()
elif(ch==3):
traverse()
elif(ch==4):
print("End")
break
else:
print("Invalid choice")
18.Write a menu based program to add, delete and display the record of
hostel using list as stack data structure in python. Record of hostel contains
the fields : Hostel number,Total Students and Total Rooms.
Source Code:host=[ ]
ch='y'
def push(host):
hn=int(input("Enter hostel number:-"))
ts=int(input("Enter Total students:-"))
tr=int(input("Enter total rooms:-"))
temp=[hn,ts,tr]
host.append(temp)
def pop(host):
if(host==[]):
print("No Record")
else:
print("Deleted Record is :",host.pop())
def display(host):
l=len(host)
print("Hostel Number\tTotal Students\tTotal Rooms")
for i in range(l-1,-1,-1):
print(host[i][0],"\t\t",host[i][1],"\t\t",host[i][2])
while(ch=='y' or ch=='Y'):
print("Sarvodaya Kanya Vidyalaya")
print("*"*40)
print("\n")
print("1. Add Record")
print("2. Delete Record")
print("3. Display Record")
print("4. Exit")
op=int(input("Enter the Choice:-"))
if(op==1):
push(host)
elif(op==2):
pop(host)
elif(op==3):
display(host)
elif(op==4):
break
ch=input("Do you want to enter more(Y/N)")
Queries Set 1 (Database Fetching records)
[1] Consider the following MOVIE table and write the SQL queries based on it.
1. Display all information from movie.
2. Display the type of movies.
3. Display movie id, movie name, total earning by showing the business done
by the movies. Calculate the business done by movie using the sum of
production cost and business cost.
4. Display movie id, movie name and production cost for all movies with
production cost greater than 150000 and less than 1000000.
5. Display the movie of type action and romance.
6. Display the list of movies which are going to release in February, 2022.
Answers:
[1] select * from movie;
2. select distinct from a movie;
3. select movieid, moviename, productioncost + businesscost “total
earning” from movie;
4. select movie_id,moviename, productioncost from movie where
producst is >150000 and <1000000;
5. select moviename from movie where type =’action’ or
type=’romance’;
6. select moviename from moview where month(releasedate)=2;
Queries Set 2
[1] Consider the following STUDENT table and write the SQL queries
based on it.
ID
12346
12347
12348
12349
12350
Name
ADITYA
HIMANI
ADITI
VISHAL
SUYASH
CLASS
12
5
5
12
12
SUBJECT
PHYSICS
SCIENCE
MATHS
CHEMISTRY
COMPUTER SCI
1. Display all information from STUDENT.
2. Display unique classes.
3. Display details of all students whose name start with A.
4. Set the subject of student as biology whose id is 12348
5. Display all information in alphabetical order by name.
Answers:
1.Select * from student;
2. Select distinct class from student;
3.Select * from student where name like ‘%A’;
4. Update student set subject = biology where id = 12348;
5. Select * from student order by name;
Queries Set 3 (DDL Commands)
Suppose your school management has decided to conduct cricket
matches between students of Class XI and Class XII. Students of each
class are asked to join any one of the four teams – Team Titan, Team
Rockers, Team Magnet and Team Hurricane. During summer
vacations, various matches will be conducted between these teams.
Help your sports teacher to do the following:
1. Create a database “Sports”.
2. Create a table “TEAM” with following considerations:
•
It should have a column TeamID for storing an integer
value between 1 to 9, which refers to unique identification of a
team.
•
Each TeamID should have its associated name
(TeamName), which should be a string of length not less than
10 characters.
•
Using table level constraint, make TeamID as the
primary key.
•
Show the structure of the table TEAM using a SQL
statement.
•
As per the preferences of the students four teams were
formed as given below. Insert these four rows in TEAM table:
•
Row 1: (1, Tehlka)
•
Row 2: (2, Toofan)
•
Row 3: (3, Aandhi)
•
Row 3: (4, Shailab)
•
Show the contents of the table TEAM using a DML
statement.
3. Now create another table MATCH_DETAILS and insert data as
shown below. Choose appropriate data types and constraints for
each attribute.
MatchID MatchDate
FirstTeamID
SecondTeamID
FirstTeamScore
M1
M2
M3
M4
M5
M6
1
3
1
2
1
2
2
4
3
4
4
3
107
156
86
65
52
97
2021/12/20
2021/12/21
2021/12/22
2021/12/23
2021/12/24
2021/12/25
Second Team
Score
93
158
81
67
88
68
Answers:
[1] create database sports
[2] Creating table with the given specification create table team ->
(teamid int(1),
-> teamname varchar(10), primary key(teamid));
Showing the structure of table using SQL statement: desc team;
Inserting data: mqsql> insert into team
-> values(1,'Tehlka');
Show the content of table – team: select * from team;
Creating another table: create table match_details
-> (matchid varchar(2) primary key,
-> matchdate date,
-> firstteamid int(1) references team(teamid),
-> s econdteamid int(1) references team(teamid),
-> firstteamscore int(3),
-> secondteamscore int(3));
Queries set 4 (Based on Two Tables)
1. Display the matchid, teamid, teamscore whoscored more than 70
in first ining along with team name.
2.
Display matchid, teamname and secondteamscore between 100
to 160.
3.
4.
5.
Display matchid, teamnames along with matchdates.
Display unique team names
Display matchid and matchdate played by Anadhi and Shailab.
Answers:
[1] select match_details.matchid, match_details.firstteamid,
team.teamname,match_details.firstteamscore from match_details,
team where match_details.firstteamid=team.teamid and
match_details.firstteamscore>70;
[2] select matchid, teamname, secondteamscore from
match_details, team where
match_details.secondteamid=team.teamid and
match_details.secondteamscore between 100 and 160;
[3] select matchid,teamname,firstteamid,secondteamid,matchdate
from match_details, team where
match_details.firstteamid=team.teamid;
[4] select distinct(teamname) from match_details, team where
match_details.firstteamid=team.teamid;
[5] select matchid,matchdate from match_details, team where
match_details.firstteamid=team.teamid and team.teamname in
(‘Aandhi’,’Shailab’);
Queries Set 5 (Group by , Order By)
Consider the following table stock table to answer the queries:
itemno
item
dcode
qty
S005
Ballpen
102
100
S003
Gel Pen
101
150
S002
Pencil
102
125
S006
Eraser
101
200
S001
Sharpner
103
210
S004
Compass
102
60
S009
A4 Papers
102
160
1.
2.
Display all the items in the ascending order of stockdate.
3.
4.
Display all the items in descending orders of itemnames.
5.
Diisplay the sum of quantity for each dcode.
unitprice
10
15
5
3
5
35
5
Display maximum price of items for each dealer individually as per
dcode from stock.
Display average price of items for each dealer individually as per
doce from stock which avergae price is more than 5.
[1] select * from stock order by stockdate;
[2] select dcode,max(unitprice) from stock group by code;
stockdate
2018/04/22
2018/03/18
2018/02/25
2018/01/12
2018/06/11
2018/05/10
2018/07/17
[3] select * from stock order by item desc;
[4] select dcode,avg(unitprice) from stock group by dcode having
avg(unitprice)>5;
[5] select dcode,sum(qty) from stock group by dcode;
23.Write program in python using mysql python connectivity to create table
student, insert data into student table and display record.
CODE:
import mysql.connector
mycon=mysql.connector.connect(host="localhost",user="root",passwd="1234")
cur=mycon.cursor()
cur.execute("create database if not exists school")
cur.execute("use school")
cur.execute("create table if not exists student(id int,name
varchar(30),class int,subject varchar(15))")
choice=0
while choice!=3:
print("1.Add new Record")
print("2.Display Record")
print("3.Exit")
choice=int(input("Enter Choice : "))
if choice==1:
i=int(input("Enter student ID: "))
n=input("Enter name of student: ")
c=int(input("Enter class in number: "))
s=input("Enter subject : ")
query="insert into student
values({},'{}',{},'{}')".format(i,n,c,s)
cur.execute(query)
mycon.commit()
print("Record Added")
elif choice==2:
query="select * from student"
cur.execute(query)
result=cur.fetchall()
for row in result:
print(row)
elif choice==3:
mycon.close()
print("Exited")
else:
print("Invalid choice!!!")
OUTPUT:
24. Write a program using mysql python connectivity to search the record of
a student using ID from student table.
CODE:
import mysql.connector
mycon=mysql.connector.connect(host="localhost",user="root",passwd="1234"
,database='school')
cur=mycon.cursor()
choice='y'
while choice=='y' or choice=='Y':
i=int(input("Enter student ID to be searched: "))
query="select * from student where id={}".format(i)
cur.execute(query)
result=cur.fetchall()
if cur.rowcount==0:
print("Student ID not found")
else:
for row in result:
print(row)
choice=input("Want to search more??? (y/n)")
OUTPUT:
25.Write a program using python mysql connectivity to update subject of a
student.
import mysql.connector
mycon=mysql.connector.connect(host="localhost",username="root",passwd="123456
",database='school')
cur=mycon.cursor()
choice='y'
while choice=='y' or choice=='Y':
cur.execute("Select * from student")
res=cur.fetchall()
for row in res:
print(row)
i=int(input("Enter student ID to update data : "))
j=input("Enter new subject :")
query="update student set subject='{}' where id={}".format(j,i)
cur.execute(query)
mycon.commit()
a=cur.rowcount
print(a,"rows updated")
cur.execute("select * from student")
result=cur.fetchall()
for row in result:
print(row)
choice=input("Want to update more??? (y/n)")
OUTPUT :
26. Write a program using python mysql connectivity to delete a record from
student table.
import mysql.connector
mycon=mysql.connector.connect(host="localhost",username="root",passwd="123456
",database='school')
cur=mycon.cursor()
choice='y'
while choice=='y' or choice=='Y':
cur.execute("Select * from student")
res=cur.fetchall()
for row in res:
print(row)
i=int(input("Enter student ID to delete : "))
query="delete from student where id={}".format(i)
cur.execute(query)
mycon.commit()
a=cur.rowcount
print(a,"rows deleted")
cur.execute("select * from student")
result=cur.fetchall()
for row in result:
print(row)
choice=input("Want to delete more??? (y/n)")
OUTPUT:
Download