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

cs practical payal 18

This document is a practical file for Computer Science (083) submitted by a student named Payal for the academic year 2023-2024. It contains a series of programming tasks in Python, including arithmetic operations, factorial calculation, Fibonacci series, palindrome checking, file handling, and MySQL queries. The document includes code snippets and outputs for each task, demonstrating various programming concepts and functionalities.
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)
4 views

cs practical payal 18

This document is a practical file for Computer Science (083) submitted by a student named Payal for the academic year 2023-2024. It contains a series of programming tasks in Python, including arithmetic operations, factorial calculation, Fibonacci series, palindrome checking, file handling, and MySQL queries. The document includes code snippets and outputs for each task, demonstrating various programming concepts and functionalities.
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/ 40

Government SARVODAYA

KANYA VIDYALAYA,
KHAJOORI KHAS

COMPUTER SCIENCE (083)


PRACTICAL FILE
2023-2024

SUBMITTED BY : Payal
CLASS : XII ‘A’
ROLL NUMBER : 18
SUBMITTED TO : Bharti mam
S.NO. PROGRAM TEACHER’S
SIGN

1a. WAP in python to enter two numbers and print the


arithmetic operations like +, -, *, //,/,% and **.
1b. WAP in python to enter two numbers and print the
arithmetic operation like +, -, *, /, //, % and ** using
functions.
2. WAP in python to find the factorial of a number using
function.
3. WAP in python to enter the numbers of terms and to
print the Fibonacci series.
4. WAP in python to accept a string and to check whether
it is a palindrome or not.
5. WAP in python to display those string which starts with
“A” from a given list.
6. WAP in python to read a file line by line and print it.
7. WAP in python to read a file line by line and display
each word separated by a #.
8. WAP in python to read a text file and display the
number of vowels/Consonants/ uppercase and
lowercase characters in the file.
9. WAP in python to remove all the lines that contain the
character ‘a’ in a file and write it to another file.
10. WAP in python to find the occurrence of a given
word/string in the file.
11. WAP 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.
12. WAP in python to create a CSV file with details of 5
students.
13. WAP in python to read a CSV file and print data.
14. Write a random number generator that generates
random number between 1 and 6(simulate a dice)
15. Write a menu based program to perform the operation
on stack in python.
16. Write a menu based program for maintaining books
details like bcode, btitle and price using stacks in
python.
17. Mysql queries set -1
18. Mysql queries set -2
19. Mysql queries set -3
20. Mysql queries set -4
21. WAP using mysql python connectivity to search the
record of a student using ID from student table.

22. WAP 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
def mul(a,b):
res=a*b
return res
def div(a,b):
res=a/b
return res
def fdiv(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
count=0
while(count<nterms):
print(n1)
nth=n1+n2
n1=n2
n2=nth
count=count+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)

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
for i in L:
if i[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")
for i 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)
for i in str:
if i.islower():
lowercase+=1
elif i.isupper():
uppercase+=1
for j in str:
if j in v:
vowels+=1
else:
if j.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. 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?(yes/no)")
f.close()
f=open('stud1.dat','rb')
student=[]
try:
while True:
student=pickle.load(f)
except EOFError:
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:
12. 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'])
for i 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:
13. 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:
14.Write a random number generator that generates random
number between 1 and 6(simulate a dice)

Code:
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:
15. Write a menu based program to perform the operation on
stack in python.

Code:

def isEmpty(S):
if len(S)==0:
return True
else:
return False
def Push(S,item):
S.append(item)
top=len(S)-1
def Pop(S):
if isEmpty(S):
return "Underflow"
else:
val = S.pop()
if len(S)==0:
top=None
else:
top=len(S)-1
return val
def Peek(S):
if isEmpty(S):
return "Underflow"
else:
top=len(S)-1
return S[top]
def Show(S):
if isEmpty(S):
print("Sorry No items in Stack ")
else:
t = len(S)-1
print("(Top)",end=' ')
while(t>=0):
print(S[t],"<==",end=' ')
t-=1
print()
# main begins here
S=[] #Stack
top=None
while True:
print("**** STACK DEMONSTRATION ******")
print("1. PUSH ")
print("2. POP")
print("3. PEEK")
print("4. SHOW STACK ")
print("0. EXIT")
ch = int(input("Enter your choice :"))
if ch==1:
val = int(input("Enter Item to Push :"))
Push(S,val)
elif ch==2:
val = Pop(S)
if val=="Underflow":
print("Stack is Empty")
else:
print("\nDeleted Item was :",val)
elif ch==3:
val = Peek(S)
if val=="Underflow":
print("Stack Empty")
else:
print("Top Item :",val)
elif ch==4:
Show(S)
elif ch==0:
print("Bye")
else:
print("Invalid Choice")
Output:
16. Write a menu based program for maintaining books details like
bcode, btitle and price using stacks in python.

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")
Output:
17.MySQL Queries Set-1 (Database Fetching records)
[1] Consider the following MOVIE table and write the SQL queries based on
it.
Movie_ID MovieName Type ReleaseDate ProductionCost BusinessCost
M001 The Kashmir Files Action 2022/01/26 1245000 1300000
M002 Attack Action 2022/01/28 1120000 1250000
M003 Loop Lapeta Thriller 2022/02/01 250000 300000
M004 Bdhai Do Drama 2022/02/04 720000 68000
M005 Shabaash Mothu Biography 2022/02/04 1000000 800000
M006 Gehriyaan Romance 2022/02/11 150000 120000
1. Display all information from movie.
2. Display the type of movies.
3. Display movieid, moviename, total_eraning by showing the business done by
the movies. Calculate the business done by movie using the sum of
productioncost and businesscost.

4.Display movieid, moviename and productioncost for all movies with production
cost greater that 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:
18. MySQL Queries Set -2
[1] Consider the following STUDENT table and write the SQL queries based
on it.
ID Name CLASS SUBJECT
12346 ADITYA 12 PHYSICS
12347 HIMANI 5 SCIENCE
12348 ADITI 5 MATHS
12349 VISHAL 12 CHEMISTRY
12350 SUYASH 12 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:


19. MySQL Queries set-3 (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. Display matchid, teamnames along with matchdates.
4. Display unique team names 5. 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’):
20. MySQL Queries Set-4 (Group by , Order By)
Consider the following table stock table to answer the queries:
itemno item dcode qty unitprice stockdate
S005 Ballpen 102 100 10 2018/04/22
S003 Gel Pen 101 150 15 2018/03/18
S002 Pencil 102 125 5 2018/02/25
S006 Eraser 101 200 3 2018/01/12
S001 Sharpner 103 210 5 2018/06/11
S004 Compass 102 60 35 2018/05/10
S009 A4 Papers 102 160 5 2018/07/17
1. Display all the items in the ascending order of stockdate.
2. Display maximum price of items for each dealer individually as per dcode from
stock.
3. Display all the items in descending orders of itemnames.
4. Display average price of items for each dealer individually as per doce from
stock which avergae price is more than 5.

5. Diisplay the sum of quantity for each dcode.

Answers:

[1] select * from stock order by stockdate


[2] Select dcode,max(unitprice) from stock group by code:

[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:


21. 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:
22. Write a program using python mysql connectivity to delete a
record from student table.

Code:
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:

You might also like