cs practical payal 18
cs practical payal 18
KANYA VIDYALAYA,
KHAJOORI KHAS
SUBMITTED BY : Payal
CLASS : XII ‘A’
ROLL NUMBER : 18
SUBMITTED TO : Bharti mam
S.NO. PROGRAM TEACHER’S
SIGN
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
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.
Answers:
Answers:
1. Display the matchid, teamid, teamscore whoscored more than 70 in first ining
along with team name.
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;
Answers:
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)
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)