Notre Dame of Holy Cross School (CBSE)

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 67

NOTRE DAME OF HOLY CROSS SCHOOL

(CBSE)

DATE: 23.04.24
Ex.No.1. Program to Calculate Factorial of a number using function.

Aim:
To write a Python program to calculate factorial of a number using function.
Algorithm:
1. Start.
2. Get input number from the user.
3. Call user defined function by passing the number as an argument.
4. Calculate factorial of the
5. passed argument and return the value.
6. Print the result.
7. Stop.

# Program to find factorial of a number


def factorial(n):
f=1
for i in range(1,n+1):
f=f*i
return f
n=int(input("Input a number to compute the factorial : "))
print("Factorial of ",n, " is: ", factorial(n))

Sample Output:
Input a number to compute the factorial: 5
Factorial of 5 is: 120

Result:
Thus, the above Python program has been executed and the output is
verified successfully.

1
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

DATE: 23.04.24
Ex.No.2. Program to find the number of upper case and lower case letters in
a string.

Aim:
To write a Python program to find the number of upper case and lowercase
letters in a string which is passed as an argument to the function.

Algorithm:
1. Start.
2. Read string input from the user.
3. Call the user defined function by passing string as an argument.
4. Find the number of upper case letters and lower case letters using
built in functions.
5. Print the result
6. Stop.

#Program to count upper and lower case letters


def string_test(s):
up=0
low=0 for c in s:
if c.isupper():
up+=1
if c.islower():
low+=1
print ("Original String : ", s)
print ("No. of Upper case characters : ", up)
print ("No. of Lower case Characters : ", low)
string=input("Enter any String:")
string_test(string)
2
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

Sample Output:

Enter any String: ND Salem


Original String: ND Salem
No. of Upper case characters: 3 No.
of Lower case Characters: 4

Result:
Thus, the above Python program has been executed and the output is
verified successfully.

3
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

DATE: 25.04.24
Ex.No.3. Program to check if a Number is a Prime or not using function.

Aim:
To write a Python program to check if a Number is a Prime or not using
function.

Algorithm:
1. Start
2. Read the number from the user and pass it to the function.
3. Call the function to check whether the entered number is prime or not.
4. If the number is prime function returns True otherwise False.
5. Print the result.
6. Stop.

#Program to check whether the given number is prime or not.


def test_prime(n):
if (n==1):
return False
elif (n==2):
return True
else:
for x in range(2,n):
if(n % x==0):
return False
return True
n=int(input("Enter any integer number:"))
4
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

if test_prime(n):
print("Entered Number is Prime")
else:
print("Entered Number is not prime")

5
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

Sample Output:

Enter any integer number: 6


Entered Number is not Prime.
Enter any integer number: 7
Entered Number is Prime

Result:
Thus, the above Python program has been executed and the output is
verified successfully.

6
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

DATE: 25.04.24

Ex.No.4. Program to find the occurrence of any word in a string.

Aim:
To write a Python program to find the occurrence of any word in a
string which is passed as an argument to function.

Algorithm:
1. Start
2. Read input string from the user.
3. Read the word to be searched in the above string.
4. Call user defined function by passing string and the word as an argument.
5. Split the passed string and count number of words.
6. Return the count value.
7. Print the result.
8. Stop.

#Program to count any word in a string.


def countWord(str1,word):
s = str1.split()
count=0
for w in s:
if w==word:
count+=1
return count

str1 = input("Enter any sentence :")


word = input("Enter word to search in sentence :")
count = countWord(str1,word)
if count==0:
print("Sorry! ",word," not present ")
else:
7
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

print(word," occurs ",count," times")

Sample Output:

Enter any sentence: Meena likes cake and Tina likes chocolate.

Enter word to search in sentence: likes


likes occurs 2 times
Enter any sentence: Meena likes cake and Tina likes chocolates.
Enter word to search in sentence: Likes
Sorry! Likes not present

Result:
Thus, the above Python program has been executed and the output is
verified successfully.

8
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

DATE: 29.04.24
Ex.No.5. Program to generate random number between 1 – 6 to simulate the
dice.

Aim:
To write a Python program to simulate the dice using random module.

Algorithm:

1. Start.
2. Repeatedly generate random number using randint(1,6) and
display the number with equal time interval.
3. Press CTRL+C to stop generating random number.
4. Print the number.
5. Stop.

#Program to simulate the dice

import random
import time
print("Press CTRL+C to stop the dice!!!") play='y'
while play=='y':
try:
while True:
for i in range(10):
print()
n = random.randint(1,6)
print(n)
time.sleep(0.5)
except KeyboardInterrupt:
print("\nYour Number is :",n)
ans=input("Play More? (Y) :")
if ans.lower()!='y':
play='n'
9
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

break

Sample Output:
Press CTRL+C to stop the
dice!!! 5
3
6
2
2
3
3
4
5
3
Your Number is: 3
Play More? (Y): n

Result:
Thus, the above Python program has been executed and the output is
verified successfully.

10
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

DATE: 29.04.24
Ex.No.6. Program to print Floyd's triangle.

Aim:
To write a Python Program to print Floyd’s Triangle.

Algorithm:
1. Start.
2. Using Nested For Loop we print the Triangle.
3. Stop.

#Floyd's triangle
n=int(input("Enter the number :"))
for i in range(n,0,-1):
for j in range(n,i-1,-1):
print (j,end=' ')
print('\n')

Sample Output: Enter


the number: 6
6
65
654
6543
65432
654321

11
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

Result:
Thus, the above Python program has been executed and the output is
verified successfully.

12
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

DATE: 14.06.24
Ex.No.7. Program to count number of lines and words in a text file.
Aim:
To write a Python program to count the number of lines and words in a text
file.

Algorithm:
1. Start.
2. Create text file using notepad and save it.
3. Open the created text file in read mode.
4. Apply readlines() to read all the lines and count the number of lines.
5. Now set the file pointer to the beginning of file and read the entire file
and count the number of words using split().
6. Print the result
7. Stop.

#Program to count number of lines and words in a text file


myfile=open("Poem.txt","r")
Lines=myfile.readlines()
NOL=len(Lines) myfile.seek(0)
words=myfile.read()
NOW=words.split()
print("Number of Lines in a text file:",NOL)
print("Number of Words in a text file:",len(NOW))

Sample Output:
Number of Lines in a text file: 4
Number of Words in a text file: 23

Result:
Thus, the above Python program has been executed and the output is
verified successfully.
13
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

14
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

DATE: 21.06.24
Ex.No.8. Program to count number of vowels and consonants in a text file.

Aim:
To write a Python program to count number of vowels and consonants in a
text file.

Algorithm:
1. Start.
2. Create text file using notepad and save it.
3. Open the created text file in read mode.
4. Read each character from the text file and check whether it is vowel
or consonant.
5. Update the counter variable.
6. Print the result
7. Stop.

# Program to count number of vowels and consonants in a text file.

myfile=open("F:\\TextFile\\Poem.txt","r")
vowels="aeiouAEIOU"
count1=0 count2=0
data=myfile.read()
for i in data:
if i in vowels:
count1=count1+1
else:
count2=count2+1
print("Number of Vowels:",count1)
print("Number of Consonants:",count2)

15
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

Sample Output:
Number of Vowels: 38 Number
of Consonants: 78

Result:
Thus, the above Python program has been executed and the output is
verified successfully.

16
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

DATE: 12.07.24
Ex.No.9. Program to copy the content of text file.

Aim:
To write a Python program to copy the content of text file which are starting
with ‘I’ to another file.

Algorithm:
1. Start.
2. Create Source text file using notepad and save it.
3. Open source file in read mode and target file in write mode.
4. Read each line from the source text file and check whether it is
starting with ‘I’.
4. Write the line into target file.
5. Print the content of target file.
6. Stop.

# Program to copy the content of text file to another file.

f=open("F:\\textfile\\poem.txt",'r')
f1=open("CopyPoem.txt","w")
while True:
txt=f.readline()
if len(txt)==0:
break
if txt[0]=='I':
f1.write(txt)
print("File Copied!")
print("Contents of new file:")
f.close()
17
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

with open("CopyPoem.txt","r") as f1:


print(f1.read())

Sample Output:

File Copied! Contents


of new file:
I love thee, O my India

Result:
Thus, the above Python program has been executed and the output is
verified successfully.

18
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

19
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

DATE: 22.07.24
Ex.No.10. Program to read a text file line by line and display each word
separated by '#'.
AIM:

To write a Python Program to Read a text file "India.txt" line by line


and display each word separated by '#'.
Algorithm:
1. Start.
2. Import pickle module and open binary file in write mode.
3. Get student details from the user and store it in dictionary variable.
4. Write the record into the file using dump().
5. Open the same file in read mode and read its content using load()
6. Display the content of file.
7. Stop.

#Program
f=open('India.txt', 'r')
contents=f.readlines()
for line in contents:
words=line.split()
for i in words:
print(i+'#', end='')
f.close()

Sample Output:

india#is#my#country#all#indians#are#my#brothers#and#sisters#i#love#my#coun
try#

Result:
Thus, the above Python program has been executed and the output is
verified successfully.
20
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

DATE: 05.08.24
Ex.No.11. Program to create binary file.
Aim:
To write a Python program to create binary file and store the details of
a student.

Algorithm:
1. Start.
2. Import pickle module and open binary file in write mode.
3. Get student details from the user and store it in dictionary variable.
4. Write the record into the file using dump().
5. Open the same file in read mode and read its content using load()
6. Display the content of file.
7. Stop.

# Program to create binary file and store the student details.

import pickle stu={}


myfile=open('student.dat','wb')
choice='y'
while choice=='y':
Rno=int(input("Enter Roll Number:"))
Name=input("Enter Name:")
Class=int(input("Enter Class(11/12):"))
Total=int(input("Enter Total Marks:"))
stu['RollNo']=Rno
stu['Name']=Name
stu['Class']=Class
stu['Marks']=Total
pickle.dump(stu,myfile)
choice=input("Do you want to add more records?(y/n)...")
myfile.close()
21
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

stu={}
fin=open('student.dat','rb')
try:
print("File Contents:")
while True:
stu=pickle.load(fin)
print(stu)
except EOFError:
fin.close()

Sample Output:

Enter Roll Number: 101


Enter Name:Rajiv
Enter Class(11/12):12 Enter
Total Marks:450
Do you want to add more records?
(y/n)...y
Enter Roll Number: 102
Enter Name:Sanjay
Enter Class(11/12):12 Enter
Total Marks: 400
Do you want to add more records? (y/n)...n File
Contents:
{'RollNo': 101, 'Name': 'Rajiv', 'Class': 12, 'Marks': 450}
{'RollNo': 102, 'Name': 'Sanjay', 'Class': 12, 'Marks': 400}

Result:
Thus, the above Python program has been executed and the output is
verified successfully.

22
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

23
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

DATE: 19.08.24

Ex.No.12. Program to update the content of binary file.

Aim:
To write a Python program to update the content of binary file.
Algorithm:
1. Start.
2. Import pickle module and open binary file in read/write mode.
3. Get the roll number of a student to identify the record.
4. Read the file using load() and identify the record to be updated.
5. Update the mark of a student and write the updated record back into the
file using dump().
6. Now display the content of updated file.
7. Stop.

# Program to update the records of the binary file.

import pickle
stu={}
found=False
myfile=open('student.dat','rb+')
n=int(input("Enter Roll number of a student to update his mark:"))
try:
while True:
pos=myfile.tell()
stu=pickle.load(myfile)
if stu['RollNo']==n:
stu['Marks']+=10
myfile.seek(pos)
pickle.dump(stu,myfile)
found=True
24
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

except EOFError:
if found==False:
print("No matching record found!")
else:
print("Record Successfully Updated!")
try:
myfile.seek(0)
print("File Content after updation:")
while True:
stu=pickle.load(myfile)
print(stu)
except EOFError:
myfile.close()
myfile.close()

Sample Output:

Enter Roll number of a student to update his mark: 101


Record Successfully Updated!
File Content after updation:
{'RollNo': 101, 'Name': 'Rajiv', 'Class': 12, 'Marks': 460}
{'RollNo': 102, 'Name': 'Sanjay', 'Class': 12, 'Marks': 400}
Sample Output 2:
Enter Roll number of a student to update his mark: 103
No matching record found!

Result:
Thus, the above Python program has been executed and the output is
verified successfully.

25
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

26
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

DATE: 09.09.24

Ex.No.13. Program to create CSV file.

Aim:

To write a Python program to create csv file to store information about


some products.

Algorithm:

1. Start.
2. Import csv module and open file in write mode.
3. Create writer object and write the product details into the file using
writerow().
4. Open the above created file in read mode using with statement.
5. Read the file using reader object.
6. Display the contents of file.
7. Stop.

# Program to create a CSV file to store product details.

import csv myfile=open('Product.csv','w',newline='')


prod_writer=csv.writer(myfile)
prod_writer.writerow(['CODE','NAME','PRICE'])
for i in range(2):
print("Product", i+1)
code=int(input("Enter Product code:"))
name=input("Enter Product Name:")
price=float(input("Enter Price:"))
prod=[code,name,price]
prod_writer.writerow(prod)
print("File created successfully!")
print("File Contents:")

27
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

print(“ ”)
myfile.close()
with open("Product.csv","r",newline='\n') as fh:
prod_reader=csv.reader(fh)
for rec in prod_reader:
print(rec)

Sample Output:
Product 1
Enter Product code: 104
Enter Product Name: Pen
Enter Price:200
Product 2
Enter Product code: 405 Enter
Product Name: Marker Enter
Price: 50
File created
successfully! File
Contents:
-----------------------
['CODE', 'NAME', 'PRICE']
['104', 'Pen', '200.0']
['405', 'Marker', '50.0']

Result:
Thus, the above Python program has been executed and the output is
verified successfully.

28
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

DATE: 14.09.24

Ex.No.14. Program to create Stack.

Aim:
To write a Python program to create Stack using an element.
Algorithm:

1. Start
2. To push an item in the stack, use the list function append list.append(item)
3. To pop an item in the stack, use the list function pop list.pop()
4. To get the top most item in the stack, write list[-1]
5. Display the content of the Stack.
6. Stop.
# Program to create a Stack using Student details.

def check_stack_isEmpty(stk):
if stk==[]:
return True
else:
return False

def push(stk,e):
stk.append(e)
top = len(stk)-1

def display(stk):
if check_stack_isEmpty(stk):
print("Stack is Empty")
else:
top = len(stk)-1
print(stk[top],"-Top")

29
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

for i in range(top-1,-1,-1):
print(stk[i])
def pop_stack(stk):
if check_stack_isEmpty(stk):
return "UnderFlow"
else:
e = stk.pop()
if len(stk)==0:
top = None
else:
top = len(stk)-1
return e

def peek(stk):
if check_stack_isEmpty(stk):
return "UnderFlow"
else:
top = len(stk)-1
return stk[top]

s=[] # An empty list to store stack elements, initially its empty top = None
# This is top pointer for push and pop operation.
def main_menu():
while True:
print("Stack Implementation")
print("1 - Push")
print("2 - Pop")
print("3 - Peek")
print("4 - Display")
print("5 - Exit")
ch = int(input("Enter the your choice:"))

30
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

if ch==1:
el = int(input("Enter the value to push an element:"))
push(s,el)
elif ch==2:
e=pop_stack(s)
if e=="UnderFlow":
print("Stack is underflow!")
else:
print("Element popped:",e)
elif ch==3:
e=peek(s)
if e=="UnderFlow":
print("Stack is underflow!")
else:
print("The element on top is:",e)
elif ch==4:
display(s)
elif ch==5:
break
else:
print("Sorry, You have entered invalid option")
main_menu()

Result:
Thus, the above Python program has been executed and the output is
verified successfully.

31
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

32
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

Output

33
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

DATE: 18.09.24

Ex.No.15. Program to create Stack using Employee details. Aim:

To write a Python program to create Stack using Employee Details.

Algorithm:

1. Start
2. To push an item in the stack, use the list function append list.append(item)
3. To pop an item in the stack, use the list function pop list.pop()
4. To get the top most item in the stack, write list[-1]
5. Display the content of the Stack.
6. Stop.

# Program to create a Stack using Employee details using (empno, name).


stk=[]
top=-1
def line():
print('~'*100)
def isEmpty():
global stk
if stk==[]:
print("Stack is empty!!!")
else:
None
def push():
global stk
global top
empno=int(input("Enter the employee number to push:"))
ename=input("Enter the employee name to push:")
stk.append([empno,ename])
top=len(stk)-1

34
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

def display():
global stk
global top
if top==-1:
isEmpty()
else:
top=len(stk)-1
print(stk[top],"<-top")
for i in range(top-1,-1,-1):
print(stk[i])
def pop_ele():
global stk
global top
if top==-1:
isEmpty()
else:
stk.pop()
top=top-1

def main():
while True:
line()
print("1. Push")
print("2. Pop")
print("3. Display")
print("4. Exit")
ch=int(input("Enter your choice:"))
if ch==1:
push()
print("Element Pushed")
elif ch==2:
pop_ele()
elif ch==3:
display()
else:
print("Invalid Choice")

35
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

break
main()

36
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

Output

Result:
Thus, the above Python program has been executed and the output is
verified successfully.

37
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

38
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

PART B
DATE: 30.09.24
EX.No.16
5 sets of SQL queries using one/two tables.

In this section Practical file computer science class 12, 5 sets of SQL queries are
required. These queries can be performed either on one or two tables. So here
we go!

Queries Set 1 (Database Fetching records)


[1] Consider the following MOVIE table and write the SQL queries based on it.

Productio Busines
Movie Movie Release
Type n s Cost
ID Name Date
Cost
The Kashmir
M001 Files Action 2022/01/26 1245000 1300000
M002 Attack Action 2023/01/28 1120000 1250000
M003 Looop Lapeta Thriller 2023/02/01 250000 300000
M004 Badhai Do Drama 2023/02/04 720000 68000
Shabaas h Biograph
M005 Mithu 2023/02/04 1000000 800000
y
M006 Gehraiyaan Romance 2023/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 doneby
the movies. Claculate the business done by movie using the sum of
productioncost and businesscost.
4. Display movieid, moviename and productioncost for all movies
with productioncost greater thatn 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, 2023.
39
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

ANSWERS
Output:

[1] Select * from movie;

mysql>select *from movie;

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 25000 300000
M004 Bdhai Do Drama 2022-02-04 72000 4800000
M005 Shabaash Mothu Biography 2022-02-04 1000000 800000
M006 Gehriyaan Romance 2022-02-11 150000 120000
6 rows in set (0.01 sec)

2. Select distinct(type) from movie;


mysql>select distinct(type) from movie;

Type
Action
Thriller
Drama
Biography
Romance

40
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

3. Select movieid, moviename, productioncost + businesscost


“total earning” from movie;
mysql>Select movie_id, moviename, productioncost + businesscost
“total earning” from movie;

Movie_i Moviename Total earning


d
M001 The Kashmir Files 2545000
M002 Attack 2370000
M003 Loop Lapeta 550000
M004 Bdhai Do 5520000
M005 Shabaash Mothu 1800000
M006 Gehriyaan 270000

4. select movie_id,moviename, productioncost from movie where producst


>150000 and productioncost<1000000;

mysql>Select movie_id, moviename, productioncost from movie where


productioncost >150000 and productioncost < 1000000;

Movie_id Moviename Productioncost


M003 Loop Lapeta 250000
M004 Bdhai Do 720000

2 rows in set(0.00 sec)

41
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

5. Select moviename from movie where type =’action’ or type=’romance’;

mysql>Select moviename frommovie where type=’action’ or


type=’romance’;

Moviename

The Kashmir Files

Attack

Gehriyaan

3 rows in set(0.00 sec)

6. Select moviename from moview where month(releasedate)=2;

mysql>Select moviename frommovie where month(releasedate)=2;

Moviename
Loop Lapeta

Bdhai Do

Shabaash Mothu

Gehriyaan

4 rows in set(0.00 sec)

42
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

Queries
Set 2 (Based on Functions)

1. Write a query to display cube of 5.


2. Write a query to display the number 563.854741 rounding off to the
next hundred.
3. Write a query to display “put” from the word “Computer”.
4. Write a query to display today’s date into DD.MM.YYYY format.
5. Write a query to display ‘DIA’ from the word “MEDIA”.
6. Write a query to display moviename – type from the table movie.
7. Write a query to display first four digits of productioncost.
8. Write a query to display last four digits of businesscost.
9. Write a query to display weekday of release dates.
10. Write a query to display dayname on which movies are going to be
released.

Answers:

[1] Select pow (5, 3);

mysql>Select pow(5,3);
Pow(5,3)
125

43
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

1 row in set (0.01 sec)

[2] Select round (563.854741,-2);

mysql>Select round(563.854741,-2);

Round(563.854741,-2)
600

1 row in set(0.01 sec)

[3] Select mid(“Computer”,4,3);

mysql>Select mid(“Computer”,4,3);

Mid(“Computer”,4,3)
put

1 row in set(0.00 sec)

[4] select
concat(day(now()),concat(‘.’,month(now()),concat(‘.’,year(now()))))
“Date”;

mysql>Select concat(day(now()),concat(now(),concat(‘.’,year(now())))) Date;


44
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

Date
9.1.2022

1 row in set(0.00 sec)

[5] Select right(“Media”,3);

mysql>Select right(“Media”,3);

right(“Media”,3)
dia

1 row1 in set(0.00 sec)

[6] Select concat(moviename,concat(‘ – ‘,type)) from movie;

mysql>Select concat(moviename,concat(‘-‘,type)) from movie;

concat(moviename,concat(‘-‘,type))
The Kashmir Files - Action
Attack - Action
Loop Lapeta – Thriller
Bdhai Do – Drama
Shabaash Mothu - Biography
Gehriyaan - Romance

6 rows in set(0.00 sec)

[7] Select left(productioncost,4) from movie;


Mysql>Select left(productioncost,4) from movie;

left(productioncost,4)
45
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

1245
1120
2500
7200
1000
1500
6 rows in set(0.00 sec)

[8] Select right(businesscost,4) from movie;


mysql> Select right(businesscost,4) from movie;

right(businesscost,4)
0000
0000
0000
0000
0000
0000
6 rows in set(0.00 sec)

[9] Select weekday(releasedate) from movie;

mysql>Select weekday(releasedate) from movie;

weekday(releasedate)
2
4
1
4
4
4
6 rows in set(0.00 sec)

[10] Select dayname(releasedate) from movie;

mysql>select dayname(releasedate) from movie;

46
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

dayname(releasedate)
Wednesday
Friday
Tuesday
Friday
Friday
Friday
6 rows in set(0.00 sec)
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 Match First Second First Second
47
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

Team Team
Date TeamID TeamID
Score Score
M1 2021/12/20 1 2 107 93
M2 2021/12/21 3 4 156 158
M3 2021/12/22 1 3 86 81
M4 2021/12/23 2 4 65 67
M5 2021/12/24 1 4 52 88
M6 2021/12/25 2 3 97 68
ANSWERS
[1] Create database sports.
mysql>create database sports;
Query Ok, 1 row affected(0.01sec)

Mysql> use Sports;


Database changed
mysql>

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

mysql>desc team;

Field Type Nill Key Default Extra

Teamid Int NO PRI NULL


48
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

Teamname Varchar(10) YES NULL

2 rows in set (0.01 sec)

Inserting data:

mqsql> insert into team values(1,'Tehlka');

mysql> inset into team


-> values (1,’Tehlka’);
Query Ok, 1 row affected (0.01 sec)

mysql> inset into team


-> values (2,’Toofan’);
Query Ok, 1 row affected (0.01 sec)

mysql> inset into team


-> values (3,’AANDHI’);
Query Ok, 1 row affected (0.01 sec)

mysql> inset into team


-> values (1,’Shailab’);
Query Ok, 1 row affected (0.01 sec)

Show the content of table – team:


select * from team;

49
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

mysql>select * from team;

Teamid Teamname
1 Tehlka
2 Toofan
3 Aandhi
4 Shailab

4 rows in set(0.00 sec)

Creating another table:


create table match_details
-> (matchid varchar(2) primary key,
-> matchdate date,
-> firstteamid int(1) references team(teamid),
-> secondteamid int(1) references team(teamid),
-> firstteamscore int(3),
-> secondteamscore int(3));

mysql>create table match_details


-> (matchid varchar(2) primary key,
-> matchdate date,
-> firstteamid int(1) references team(teamid),
-> secondteamid int(1) references team(teamid),
-> firstteamscore int(3),
-> secondteamscore int(3));
Query OK,0 rows affected, 4 warnings (0.03 sec)

mysql>Select * from match_details;

Matchid Matchdate Firstteamid Secondteami Firstteamscore Secondteamscore


d
M1 2021-12-20 1 2 107 93

50
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

M2 2021-12-21 3 4 156 158

M3 2021-12-22 1 3 86 81

M4 2021-12-23 2 4 65 67

M5 2021-12-24 1 4 52 88

M6 2021-12-25 2 3 97 68

6 rows in set(0.01 sec)

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

mysql> select * from match_details;

Matchid Matchdate Firstteamid Secondteami Firstteamscore Secondteamscore


51
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

d
M1 2021-12-20 1 2 107 93

M2 2021-12-21 3 4 156 158

M3 2021-12-22 1 3 86 81

M6 2021-12-25 2 3 97 68

4 rows in set(0.01 sec)

[2] select distinct(teamname) from match_details, team where


match_details.firstteamid = team.teamid;

mysql>select distinct(teamname) from


match_details,team where
match_details.firstteamid=team.teamid;

Teamname
Tehlka
Aandhi
Shailab
Toofan
4 rows in set(0.03 sec)

[3] select matchid,matchdate from match_details, team where


match_details.firstteamid = team.teamid and team.teamname in

52
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

(‘Aandhi’,’Shailab’);

mysql>select matchid,matchdate from match_details,team where


match_details.firtstteamid=team.teamid and team.teamname in
(‘Aandhi’, ‘Shailab’);

Matchid Matchdate
M2 2021-12-21
M4 2021-12-23
2 rows in set(0.00 sec)

[4] select matchid, teamname, secondteamscore from match_details, team


where match_details.secondteamid = team.teamid and
match_details.secondteamscore between 100 and 160;

mysql>select matchid,teamname,secondteamscore from match_details,


team where match_details.secondteamid=team.teamid and
match_details.secondscore between 100 and 160;

Matchid Teamname Secondteamscore


M2 Shailab 158

1 row in set (0.00 sec)

[5] select matchid, teamname, firstteamid, secondteamid,matchdate


from match_details, team where
match_details.firstteamid = team.teamid;
53
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

mysql>select matchid,teamname, firstteamid, secondteamid,


matchdate from match_details, team where
match_details.firstteamid=team.teamid;

Matchid Teamname Firstteamid Secondteamid Matchdate

M1 Tehlka 1 2 2021-12-20
M2 Aandhi 3 4 2021-12-21
M3 Tehlka 1 3 2021-12-22
M4 Toofan 2 4 2021-12-23
M5 Tehlka 1 4 2021-12-25
M6 Toofan 2 3 2021-12-25

Queries
Set 5 (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
54
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

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. Display the sum of quantity for each dcode.

[1] select * from stock order by stockdate;

mysql>select * from stock order by stockdate;

Itemno Item Dcode Qty Unitprice Stockdate


S006 Eraser 101 200 3 2018-01-12
S002 Pencil 102 125 5 2018-02-25
S003 Gel Pen 101 150 15 2018-03-18
S005 Ballpen 102 100 10 2018-04-22
S004 Compass 102 60 35 2018-05-10
S009 A4 Papers 102 160 5 2018-07-17
S001 Shrapner 103 210 5 2018-11-06
7 rows in set(0.00 sec)
[2] select dcode, max(unitprice) from stock group by dcode;

mysql> select dcode,max(unitprice) from stock group by dcode;

Dcode Max(unitprice)
103 5
55
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

102 35
101 15
3 rows in set (0.01 sec)

[3] select * from stock order by item desc;

mysql>select * from stock order by item desc;

Itemno Item Dcode Qty Unitprice Stockdate


S001 Shrapner 103 210 5 2018-11-06
S002 Pencil 102 125 5 2018-02-25
S003 Gel Pen 101 150 15 2018-03-18
S006 Eraser 101 200 3 2018-01-12
S004 Compass 102 60 35 2018-05-10
S005 Ballpen 102 100 10 2018-04-22
S009 A4 Papers 102 160 5 2018-07-17
7 rows in set (0.01 sec)

[4] select dcode,avg(unitprice) from stock group by dcode having


avg(unitprice)>5;

mysql>select dcode,avg(unitprice) from stock group by dcode having


avg(unitprice)>5;

Dcode Avg(unitprice)
102 13.7500
101 9.0000

2 rows in set (0.00 sec)

[5] select dcode, sum(qty) from stock group by dcode;

56
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

mysql>select dcode,sum(qty) from stock group by dcode;

Dcode Sum(qty)
103 210
102 445
101 350

3 rows in set(0.03 set)

57
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

PYTHON-MYSQL CONNECTIVITY PROGRAMS

DATE: 15.11.24

Ex.No.17. Program to fetch all the records from Student Table. Aim:

To write a Python program to fetch all the records from the Student Table.

Algorithm:

1. Start.
2. Import mysql.connector module.
3. Establish connection using connect().
4. Create Cursor instance using cursor().
5. Fetch all the records from the table using fetchall().
6. Traverse the result set using for loop and print the records.
7. Close the connection using close().
8. Stop.

Program:

# Program to fetch all the records from Student table import


mysql.connector as sqltor
con=sqltor.connect(host="localhost",user="root",passwd="mysql1233",d
atabase="NDHCS")
if con.is_connected==False:
print('Error')
cursor=con.cursor()
cursor.execute("select * from Student")
data=cursor.fetchall()
count=cursor.rowcount
print("No.Rows:",count)
for row in data:
print(row)
con.close()

58
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

Sample Output:

Result:
Thus, the above query has been executed and the output is
verified successfully.

59
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

DATE: 21.11.24

Ex.No.18. Program to fetch records from Student Table.

Aim:

To write a Python program to fetch the records from the Student


Table which satisfies the given condition.

Algorithm:

1. Start.
2. Import mysql.connector module.
3. Establish connection using connect().
4. Create Cursor instance using cursor().
5. Execute SQL query with string formatting.
6. Fetch all the records from the table using fetchall().
7. Traverse the result set using for loop and print the records.
8. Close the connection using close().
9. Stop.

Program:

# Program to fetch records which satisfies the given condition.


import mysql.connector as sqltor
con=sqltor.connect(host="localhost",user="root",passwd="mysql123",datab
ase="NDHCS")
if con.is_connected==False:
print('Error')
cur=con.cursor()

60
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

cur.execute("select * from student where percentage>={}".format(80))


data=cur.fetchall()
count=cur.rowcount
print("No.Rows:",count)
for row in data:
print(row)
con.close()

Sample Output:

Result:
Thus, the above query has been executed and the output is
verified successfully.

61
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

DATE: 03.12.24

Ex: No.19. Program to insert records into Table.

Aim:

To write a Python program to insert new record into Student Table.

Algorithm:

1. Start.
2. Import mysql.connector module.
3. Establish connection using connect().
4. Create Cursor instance using cursor().
5. Execute insert command with string formatting and apply commit() to
save the changes permanently.
6. Execute select query and fetch all the records using fetchall().
7. Traverse the result set using for loop and print the records.
8. Close the connection using close().
9. Stop.

Program:
# Program to insert new record into table.

import mysql.connector as sqltor


con=sqltor.connect(host="localhost",user="root",passwd="mysql123",datab
ase="NDHCS")
if con.is_connected==False:
print('Error')

62
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

cur=con.cursor()

query="insert into student values({},'{}',{},'{}',{},{})".


format(106,'Raj',12,'A',430,86)
cur.execute(query)
con.commit()
print("Record Inserted")
cur.execute("Select * from Student")
print("Table after insertion")
data=cur.fetchall()
for row in data:
print(row)
con.close()

Sample Output:

Result:
Thus, the above query has been executed and the output is
verified successfully.

63
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

64
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

DATE: 03.12.24

Ex.No.20. Program to update records in a table.

Aim:

To write a Python program to update record in a table.

Algorithm:

1. Start.
2. Import mysql.connector module.
3. Establish connection using connect().
4. Create Cursor instance using cursor().
5. Execute insert command with string formatting and apply commit() to
save the changes permanently.
6. Execute select query and fetch all the records using fetchall().
7. Traverse the result set using for loop and print the records.
8. Close the connection using close().
9. Stop.

Program:

# Program to update record in


a table import mysql.connector
as sqltor
con=sqltor.connect(host="localhost",user="root",passwd="mysql123",datab
ase="NDHCS")
if con.is_connected==False:
print('Error')
cur=con.cursor()

65
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

query="update student set section='{}' where


name='{}'".format('B','Neha')
cur.execute(query)
con.commit() print("Record Updated")
cur.execute("Select * from Student")
print("Table after Updation")
data=cur.fetchall()
for row in data:
print(row)
con.close()

Sample Output:

Result:
Thus, the above query has been executed and the output is
verified successfully.

66
NOTRE DAME OF HOLY CROSS SCHOOL
(CBSE)

67

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy