0% found this document useful (0 votes)
272 views46 pages

Xii Computer Science Practical Programs 2024-25

practical programs

Uploaded by

tharani1278
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)
272 views46 pages

Xii Computer Science Practical Programs 2024-25

practical programs

Uploaded by

tharani1278
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/ 46

XII – COMPUTER SCIENCE (083)

2024-25
PRACTICAL PROGRAMS

Details of Practical Examination


Maximum Marks : 30
S.no Area Marks
1 Practical Lab Test:
1. Python program 8
2. SQL queries (Any 4 queries based on one or two tables) 4
2 Completed Practical Record Note Book (Report File) 7
3 Project (using concepts learnt in Classes 11 and 12) 8
4 Viva voce 3
TOTAL 30 M
Ex.No. Programs

1 ARITHMETIC OPERATION
2 USER-DEFINED FUNCTIONS
3 STRING FUNCTIONS
4 STRING MANIPULATION
5 GENERATING INTEGER AND REAL RANDOM NUMBERS
6 CONVERSION USING MATHEMATICAL FUNCTIONS
7 EXCEPTION HANDLING

8 ROOTS OF QUADRATIC EQUATION USING CMATH


9 WRITE AND READ A TEXT FILE
10 FILE COPY
11 SEARCHING IN BINARY FILE
12 CSV FILE
13 READ TEXT FILE USING TELL AND SEEK
14 OPERATIONS ON STACK
15 EVALUATION OF POSTFIX EXPRESSION
16 CREATING DATABASE AND TABLE BY USING PYTHON-MYSQL
INSERTING, SEARCHING AND DISPLAYING RECORDS BY USING PYTHON-
17
MYSQL
SEARCHING, UPDATING AND DISPLAYING RECORDS BY USING PYTHON-
18
MYSQL
19 DISPLAYING RECORDS BY USING PYMYSQL IN PYTHON-MYSQL

20 SQL QUERY - CREATION, INSERTION AND DISPLAY

21 SQL QUERY – UPDATE AND DISPLAY

22 SQL QUERY - ALTER, DELETE AND DROP


SQL QUERY USING TWO TABLES ON STOCK DATA
23

24 SQL QUERY USING TWO TABLES ON STUDENT DATA


1. ARITHMETIC OPERATION
GIVEN PROBLEM:
Write a menu driven Program to perform Arithmetic operations (+,-,*,/,%,//) based on the
user's choice
AIM: To write a menu-driven Program to perform Arithmetic operations.

SOURCE CODE:
choice='y'
while (choice=='y' or choice == 'Y'):
print("\tMenu")
print("\t~~~~")
print("1 - Addition (+)")
print("2 - Subtraction (-)")
print("3 - Multiplication (*)")
print("4 - Division (/)")
print("5 - Modulus (%)")
print("6 - Floor Division (//)")
op = int(input("Enter your Choice : "))
if op in (1,2,3,4,5,6):
a = int(input("\nEnter the First Number : "))
b = int(input("Enter the Second Number : "))
if (op==1):
result = a+b
print("The Addition Value is ",result)
if (op==2):
result = a-b
print("The Subtraction Value is ",result)
if (op==3):
result = a * b
print("The Product Value is ",result)
if (op==4):
if (b==0):
print("Error : Divisible by 0")
else:
result = a/b
print("The Division Value is %.2f" %result)
if (op==5):
result = a%b
print("The Modulus Value is ",result)
if (op==6):
result = a//b
print("The Floor Division Value is ",result)
else:
print("You have entered invalid choice ")
choice=input("\nIf you want to Continue press 'y' or press any key to exit: ")
OUTPUT:
Menu
~~~~
1 - Addition (+)
2 - Subtraction (-)
3 - Multiplication (*)
4 - Division (/)
5 - Modulus (%)
6 - Floor Division (//)
Enter your Choice : 6

Enter the First Number : 50


Enter the Second Number : 6
The Floor Division Value is 8

If you want to Continue press 'y' or press any key to exit: y

Menu
~~~~
1 - Addition (+)
2 - Subtraction (-)
3 - Multiplication (*)
4 - Division (/)
5 - Modulus (%)
6 - Floor Division (//)
Enter your Choice : 4

Enter the First Number : 100


Enter the Second Number : 3
The Division Value is 33.33

If you want to Continue press 'y' or press any key to exit:


2. USER-DEFINED FUNCTIONS
GIVEN PROBLEM:
Write a menu-driven Python Program to perform sum, max, min, and sorting of numbers
using user-defined functions in list

AIM: To write a menu-driven Python Program to perform sum, max, min, sorting of number
using user-defined functions in list.

SOURCE CODE:

def sumlist(a):
sum=0
for i in a:
sum = sum + i
return(sum)

def maxlist(a):
max=a[1]
for i in a:
if i > max :
max = i
return(max)

def minlist(a):
min=a[1]
for i in a:
if i < min :
min = i
return(min)

def bubblesort(a):
n=len(a)
for i in range(n):
for j in range(0,n-i-1):
if a[j] > a[j+1]:
a[j],a[j+1] = a[j+1],a[j]
return(a)

ch = 'y'
funcList = []
n = int(input("\nEnter the number of elements in the list : "))
for i in range(n):
print("Enter the ",i+1," Element : ",end=" ")
funcList.append(int(input()))
while(ch=='y' or ch=='Y'):
print("\tFUNCTIONS IN LIST")
print("\t~~~~~~~~~~~~~~~~")
print("1 - To find Sum of given List elements ")
print("2 - To find Maximum in the given List ")
print("3 - To find Minimum in the given List ")
print("4 - To Sort the List ")
op = int(input("Enter your Choice : "))
if op in (1,2,3,4):
print(funcList)
if (op==1):
print("The Sum of elements in the list is ",sumlist(funcList))
if (op==2):
print("The Maximum value in the given list is ",maxlist(funcList))
if (op==3):
print("The Minimum value in the given list is ",minlist(funcList))
if (op==4):
print("The Sorted List is ",bubblesort(funcList))
else:
print("You have entered invalid Choice ")
ch=input("\nDo you want to Continue (y/n) : ")
OUTPUT:
Enter the number of elements in the list : 9
Enter the 1 Element : 5
Enter the 2 Element : -98
Enter the 3 Element : -7
Enter the 4 Element : 258
Enter the 5 Element : 376
Enter the 6 Element : 94
Enter the 7 Element : 62
Enter the 8 Element : -54
Enter the 9 Element : 47
FUNCTIONS IN LIST
~~~~~~~~~~~~~~~~
1 - To find Sum of given List elements
2 - To find Maximum in the given List
3 - To find Minimum in the given List
4 - To Sort the List
Enter your Choice : 1
[5, -98, -7, 258, 376, 94, 62, -54, 47]
The Sum of elements in the list is 683

Do you want to Continue (y/n) : y


FUNCTIONS IN LIST
~~~~~~~~~~~~~~~~
1 - To find Sum of given List elements
2 - To find Maximum in the given List
3 - To find Minimum in the given List
4 - To Sort the List
Enter your Choice : 2
[5, -98, -7, 258, 376, 94, 62, -54, 47]
The Maximum value in the given list is 376

Do you want to Continue (y/n) : y


FUNCTIONS IN LIST
~~~~~~~~~~~~~~~~
1 - To find Sum of given List elements
2 - To find Maximum in the given List
3 - To find Minimum in the given List
4 - To Sort the List
Enter your Choice : 4
[5, -98, -7, 258, 376, 94, 62, -54, 47]
The Sorted List is [-98, -54, -7, 5, 47, 62, 94, 258, 376]

Do you want to Continue (y/n) : n


3. STRING FUNCTIONS
GIVEN PROBLEM:
Write a menu driven Python Program to implement String functions (String Length, String
Concatenation, Title, UpperCase, LowerCase, Find String)
AIM: To write a menu driven Python Program to implement String functions.
import string
str1 = input("\nEnter the String : ")
while True:
print("\tSTRING FUNCTIONS")
print("\t-----------------------------")
print("1 - String Length")
print("2 - String Concatenation")
print("3 - Title Case")
print("4 - Upper Case")
print("5 - Lower Case")
print("6 - Find String")
print("7 - Exit")
op = int(input("Enter your Choice : "))
if (op==1):
print("\n Length of the String : ",len(str1))
elif (op==2):
str2 = input("\n Enter the Second String : ")
print("\n The Concatenated String is : ", (str1+str2))
elif (op==3):
print("\n Title Case of the String : ",str1.title())
elif (op==4):
print("\n Upper Case of the String : ",str1.upper())
elif (op==5):
print("\n Lower Case of the String : ",str1.lower())
elif (op==6):
str3 = input("\n Enter the String to be found : ")
if (str1.find(str3)!=-1):
print("String Found")
else:
print("String not Found")
elif (op==7):
break
else:
print("Invalid option selected, ")
OUTPUT:
Enter the String: the function should return a value
STRING FUNCTIONS
-----------------------------
1 - String Length
2 - String Concatenation
3 - Title Case
4 - Upper Case
5 - Lower Case
6 - Find String
7 - Exit
Enter your Choice : 1

Length of the String : 34


STRING FUNCTIONS
-----------------------------
1 - String Length
2 - String Concatenation
3 - Title Case
4 - Upper Case
5 - Lower Case
6 - Find String
7 - Exit
Enter your Choice : 3

Title Case of the String : The Function Should Return A Value


STRING FUNCTIONS
-----------------------------
1 - String Length
2 - String Concatenation
3 - Title Case
4 - Upper Case
5 - Lower Case
6 - Find String
7 - Exit
Enter your Choice : 6

Enter the String to be found : return


String Found
4. STRING MANIPULATION

GIVEN PROBLEM:
Write a Program to find the Number of vowels, words, Uppercase and Special characters in
a given sentence

AIM: To Write a Program to find the Number of vowels, words, Uppercase and Special
characters in a given sentence

SOURCE CODE:

def vowels(a):
v=0
for i in a:
if i in 'AEIOUaeiou':
v=v+1
print("\nThe Number of Vowels in the given sentence is : ",v)

def upper(a):
u=0
for i in a:
if i.isupper() == 1:
u=u+1
print("\nThe Number of Uppercase characters in the given sentence is : ",u)

def symbols(a):
s=0
for i in a:
if i.isalnum() == 0:
s=s+1
print("\nNumber of Special Characters in the given Sentence is : ",s)

def words(a):
w=1
for i in a:
if i.isspace() == 1:
w=w+1
print("\nThe Number of Words in the given sentence is : ",w)

str = input("\nEnter the Sentence : ")


vowels(str)
upper(str)
symbols(str)
words(str)
OUTPUT:

Enter the Sentence : The aim of the class project is to create useful IT application

The Number of Vowels in the given sentence is : 22

The Number of Uppercase characters in the given sentence is : 3

Number of Special Characters in the given Sentence is : 11

The Number of Words in the given sentence is : 12


5. GENERATING INTEGER AND REAL RANDOM NUMBERS

GIVEN PROBLEM:
Write a program to generate integer and real random numbers
AIM:
To write a program to generate integer and real random numbers

SOURCE CODE:

import random

def generate_random_integers(count, lower_bound, upper_bound):


rdint=[]
for i in range(count):
rdint.append(random.randint(lower_bound,upper_bound))
return rdint

def generate_random_floats(count, lower_bound, upper_bound):


rdint=[]
for i in range(count):
rdint.append(random.uniform(lower_bound,upper_bound))
return rdint

count = int(input("How many Random Numbers should be generated: "))


int_lower_bound = int(input("Enter the lower bound for Integer Numbers: "))
int_upper_bound = int(input("Enter the upper bound for Integer Numbers: "))
float_lower_bound = float(input("Enter the lower bound for Real Numbers: "))
float_upper_bound = float(input("Enter the upper bound for Real Numbers: "))

random_integers = generate_random_integers(count, int_lower_bound, int_upper_bound)


print("\nRandom Integers: " , random_integers)
random_floats = generate_random_floats(count, float_lower_bound, float_upper_bound)
print("\n Random Real Numbers ",random_floats)
OUTPUT

How many Random Numbers should be generated: 10


Enter the lower bound for Integer Numbers: 30
Enter the upper bound for Integer Numbers: 70
Enter the lower bound for Real Numbers: 10.8
Enter the upper bound for Real Numbers: 36.7

Random Integers: [52, 51, 40, 46, 45, 65, 46, 69, 41, 69]

Random Real Numbers [24.54441468650451, 25.914294529801026, 19.778078005345325,


14.16469357064886, 24.798252767217306, 14.378548967376215, 28.290297874681983,
27.33151668427827, 31.083329186906816, 33.24791537501096]
6. CONVERSION USING MATHEMATICAL FUNCTIONS

GIVEN PROBLEM:
Write a menu-driven program to convert the given decimal number to binary, octal and
hexadecimal numbers using mathematical functions
AIM:
To write a menu-driven program to convert the given decimal number to binary, octal and
hexadecimal numbers using mathematical functions

SOURCE CODE:

import math

while True:
print("\nConversion using Mathematical Functions")
print("----------------------------------------------------------")
print("1. To Binary Number ")
print("2. To Octal Number ")
print("3. To Hexadecimal Number ")
print("4. Exit ")
choice = int(input("Enter your Choice "))
if choice in (1,2,3,4):
if choice == 1:
num = int(input("Enter Decimal Number to be converted as Binary Number "))
str1 = bin(num)
print("The Binary Number is ",str1[2:])
if choice == 2:
num = int(input("Enter Decimal Number to be converted as Octal Number "))
str1 = oct(num)
print("The Octal Number is ",str1[2:])
if choice == 3:
num = int(input("Enter Decimal Number to be converted as Hexadecimal Number "))
str1 = hex(num)
print("The Hexadecimal Number is ",str1[2:])
if choice == 4:
break
else:
print("You have entered invalid choice ")
OUTPUT

Conversion using Mathematical Functions


----------------------------------------------------------
1. To Binary Number
2. To Octal Number
3. To Hexadecimal Number
4. Exit
Enter your Choice 3
Enter Decimal Number to be converted as Hexadecimal Number 31
The Hexadecimal Number is 1f

Conversion using Mathematical Functions


----------------------------------------------------------
1. To Binary Number
2. To Octal Number
3. To Hexadecimal Number
4. Exit
Enter your Choice 1
Enter Decimal Number to be converted as Binary Number 32
The Binary Number is 100000
7. EXCEPTION HANDLING

GIVEN PROBLEM:
Write a program to divide two numbers by a user-defined function using the try and except
block method

AIM:
To write a program to divide two numbers by a user-defined function using the try and except block
method

SOURCE CODE:

def divide_numbers(numerator, denominator):


try:
result = numerator / denominator
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
return None
else:
return result
finally:
print("Execution of the Division function is over")

try:
num = int(input("Enter the numerator: "))
denom = int(input("Enter the denominator: "))
result = divide_numbers(num, denom)
if result is not None:
print("The Result of the division is ",result)
except ValueError:
print("Please Give Integer Number only" )
except:
print("Error Occurred in this program")
OUTPUT:

Enter the numerator: 10


Enter the denominator: 5
Execution of the Division function is over
The result of the division is 2.0

Enter the numerator: 25


Enter the denominator: 0
Error: Division by zero is not allowed.
Execution of the Division function is over

Enter the numerator: hello


Please Give Integer Number only
8. ROOTS OF QUADRATIC EQUATION USING CMATH
GIVEN PROBLEM:
Write a program to find roots of Quadratic Equation using cmath module for complex
numbers

AIM:
To write a program to find roots of Quadratic Equation using cmath module for complex
numbers

SOURCE CODE:

import math,cmath
try:
def find_roots(a, b, c):
discriminant = b**2 - 4*a*c
if discriminant ==0:
print("\nThe roots are real and equal ")
root1 = (-b + math.sqrt(discriminant)) / (2*a)
root2 = (-b - math.sqrt(discriminant)) / (2*a)
elif discriminant > 0:
print("\nThe roots are real and different")
root1 = (-b + math.sqrt(discriminant)) / (2*a)
root2 = (-b - math.sqrt(discriminant)) / (2*a)
else:
print("\nThe roots are imaginary")
root1 = (-b + cmath.sqrt(discriminant)) / (2*a)
root2 = (-b - cmath.sqrt(discriminant)) / (2*a)
return (root1, root2)

print("Quadratic Equation: ax^2 + bx + c = 0")


a = int(input("Enter coefficient a: "))
b = int(input("Enter coefficient b: "))
c = int(input("Enter coefficient c: "))
,

if a == 0:
print("Coefficient 'a' cannot be zero for a quadratic equation.")
else:
roots = find_roots(a, b, c)
print(f"The roots of the quadratic equation are: {roots[0]} and {roots[1]}")
except ValueError:
print ("Enter integer value only ")
except Exception as Err:
print("Error is ",Err)
OUTPUT

Quadratic Equation: ax^2 + bx + c = 0


Enter coefficient a: 1
Enter coefficient b: -6
Enter coefficient c: 9

The roots are real and equal


The roots of the quadratic equation are: 3.0 and 3.0

Quadratic Equation: ax^2 + bx + c = 0


Enter coefficient a: 1
Enter coefficient b: -6
Enter coefficient c: 8

The roots are real and different


The roots of the quadratic equation are: 4.0 and 2.0

Quadratic Equation: ax^2 + bx + c = 0


Enter coefficient a: 1
Enter coefficient b: 2
Enter coefficient c: 3

The roots are imaginary


The roots of the quadratic equation are: (-1+1.4142135623730951j) and
(-1-1.4142135623730951j)
9. WRITE AND READ A TEXT FILE

GIVEN PROBLEM:
Write a Python program to create a text file to store information inputted by the user and
display the same with each word separated by "*".
AIM:

To write a Program to create and display a text file.


SOURCE CODE:

f = open("csnotes.txt","w")
ch = 'y'
while (ch=='y' or ch=='Y'):
str = input("Enter the Line to be inserted in the text file : ")
f.write(str)
ch = input("Do you want to enter some more lines : ")
f.write("\n")
f.close()
print("\n 'Text.txt' File has been successfully created")
print("\n Content of the File")
f = open("text.txt","r")
s = f.read()
l = s.split(" ")
for i in l:
print(i,end="*")

OUTPUT:

Enter the Line to be inserted in the text file : Hi! Hello How are you?
Do you want to enter some more lines : y
Enter the Line to be inserted in the text file : I like Python Programming Language
Do you want to enter some more lines : y
Enter the Line to be inserted in the text file : It is case sensitive language
Do you want to enter some more lines : n
'csnotes.txt' File has been successfully created

Content of the File


Hi!*Hello*How*are*you?
I*like*Python*Programming*Language
It*is*case*sensitive*language
10. FILE COPY
GIVEN PROBLEM:
Write a Python program to copy one file to another file without vowels.

AIM:
To write a Python Program, copy one file to another file without vowels.

SOURCE CODE:

f = open("Mytext.txt","w")
ch = 'y'
while (ch=='y' or ch=='Y'):
str = input("Enter the Line to be inserted in the text file : ")
f.write(str)
ch = input("Do you want to enter some more lines : ")
f.write("\n")
f.close()
print("\n 'Text.txt' File has been successfully created")
print("\n Content of the File after removing Vowels")
f = open("text.txt","r")
f1 = open("co.txt","w")
s = f.read()
for i in s:
if i not in "aeiouAEIOU":
f1.write(i)
f.close()
f1.close()
f1 = open("co.txt","r")
b = f1.read()
print(b)
f1.close()
OUTPUT

Enter the Line to be inserted in the text file : Hi! Hello How are you
Do you want to enter some more lines : y
Enter the Line to be inserted in the text file : I like python programming language
Do you want to enter some more lines : y
Enter the Line to be inserted in the text file : Today is a Good Day
Do you want to enter some more lines : n

'Mytext.txt' File has been successfully created

Content of the File after removing Vowels


H! Hll Hw r y
lk pythn prgrmmng lngg
Tdy s Gd Dy
11. SEARCHING IN BINARY FILE

GIVEN PROBLEM:

Write a Python Program to Create a binary file with roll number and name. Search for a
given roll number and display the name, if not found display appropriate message. Python
program to copy one file to another file without vowels.

AIM: To write a Python Program to Create a binary file with roll number and name.

SOURCE CODE:

import pickle

def create():
f = open("students.dat",'ab')
opt = 'y'
while (opt == 'y' or opt == 'Y'):
rollno = int(input("Enter the roll number : "))
name = input("Enter the Name : ")
l = [rollno,name]
pickle.dump(l,f)
opt = input("Do you want to add another student detail (y/n) : ")
f.close()

def search():
f = open("Students.dat","rb")
no=int(input("Enter Roll number of student to search : "))
found = 0
try:
while True:
s = pickle.load(f)
if s[0] == no:
print("The searched Roll No. is found and details are : ",s)
found = 1
break
except:
f.close()
if found == 0:
print("The Searched Roll No. is not found")

create()
search()
OUTPUT:

Enter the roll number : 1


Enter the Name : Anbu
Do you want to add another student detail (y/n) : y
Enter the roll number : 2
Enter the Name : Siva
Do you want to add another student detail (y/n) : y
Enter the roll number : 3
Enter the Name : Kani
Do you want to add another student detail (y/n) : n
Enter Roll number of student to search : 2
The searched Roll No. is found and details are : [2, 'Siva']
12. READ TEXT FILE USING TELL AND SEEK

GIVEN PROBLEM:
Write a program to write a text file ‘sample.txt’ and
 Use tell () to get the current position of the file pointer and print it.
 Uses seek (0) to move the file pointer to the beginning of the file and reads the entire
content.
 Moves the file pointer back to the position after the first line using seek (position) and reads
the remaining content.

AIM:
To write a program to write a text file and to read the file using tell() and seek()

SOURCE CODE:

def write_to_file(filename):
with open(filename, 'w') as file:
file.write("Nurture Your Body, Nourish Your Soul.\n")
file.write("Empower Your Life with Wellness.\n")
file.write("Empowering Dreams through Knowledge.\n")
file.write("Preserve Today for a Brighter Tomorrow.")

def read_with_seek_and_tell(filename):
with open(filename, 'r') as file:
first_line = file.readline()
print("First line: ",first_line.strip())
position = file.tell()
print("\nFile pointer is at position after first line read: ",position)
file.seek(0)
print("\nReading from the beginning of the file:")
content = file.read()
print(content)
file.seek(position)
print("\nReading from the position after the first line:")
remaining_content = file.read()
print(remaining_content)

filename = 'sample.txt'
write_to_file(filename)
read_with_seek_and_tell(filename)

OUTPUT
First line: Nurture Your Body, Nourish Your Soul.

File pointer is at position after first line read: 39

Reading from the beginning of the file:


Nurture Your Body, Nourish Your Soul.
Empower Your Life with Wellness.
Empowering Dreams through Knowledge.
Preserve Today for a Brighter Tomorrow.

Reading from the position after the first line:


Empower Your Life with Wellness.
Empowering Dreams through Knowledge.
Preserve Today for a Brighter Tomorrow.
13. CSV FILE

GIVEN PROBLEM:
Write a Python program to create a CSV file to store Empno, Name, Salary and search any
Empno and display Name, Salary and if not found display appropriate message.

AIM: To write a Python program to Create a CSV file to store Employee Details.

SOURCE CODE:

import csv

def create():
f = open("emp.csv","a",newline='')
w = csv.writer(f)
op = 'y'
while (op == 'y' or op == 'Y'):
no = int(input("Enter Employee Number : "))
name = input("Enter Employee Name : ")
sal = float(input("Enter Employee Salary : "))
l=[no,name,sal]
w.writerow(l)
op=input("Do you want to continue (y/n)? : ")
f.close()

def search():
f = open("emp.csv","r",newline='\r\n')
no = int(input("Enter Employee number to search : "))
found = 0
row = csv.reader(f)
for data in row:
if data[0] == str(no):
print("\n Employee Details are : ")
print(" ~~~~~~~~~~~~~~~~~~~~")
print("Name : ",data[1])
print("Salary : ",data[2])
print(" ~~~~~~~~~~~~~~~~~~~~")
found = 1
break
if found ==0:
print("The Searched Employee number is not found")
f.close()

create()
search()
OUTPUT

Enter Employee Number : 1


Enter Employee Name : Abi
Enter Employee Salary : 10000
Do you want to continue (y/n)? : y
Enter Employee Number : 2
Enter Employee Name : Hema
Enter Employee Salary : 40000
Do you want to continue (y/n)? : y
Enter Employee Number : 3
Enter Employee Name : Sanjay
Enter Employee Salary : 30000
Do you want to continue (y/n)? : n
Enter Employee number to search : 2

Employee Details are :


~~~~~~~~~~~~~~~~~~~~
Name : Hema
Salary : 40000.0
~~~~~~~~~~~~~~~~~~~~
14. OPERATIONS ON STACK

GIVEN PROBLEM:
Write a Python program to implement stack operations using the list.

AIM: To write a Python program to implement stack operations using the list.

SOURCE CODE:

def push():
ele = int(input("Enter the element which you want to push : "))
stack.append(ele)

def pop():
if stack == []:
print("Stack is Empty / Underflow")
else:
print("The deleted element is : ", stack.pop())

def peek():
top = len(stack)-1
print("The top most element of stack is : ",stack[top])

def disp():
top = len(stack)-1
print("The stack elements are : ")
for i in range(top,-1,-1):
print(stack[i])

stack = []
op = 'y'
while (op =='y' or op == 'Y'):
print("Stack Operations")
print("~~~~~~~~~~~~~~~~")
print("1 - PUSH")
print("2 - POP")
print("3 - PEEK")
print("4 - DISPLAY")
print("~~~~~~~~~~~~~~~~")
op = int(input("Enter your Choice : "))

if op == 1:
push()
elif op == 2:
pop()
elif op == 3:
peek()
else:
disp()

op = input("Do you want to perform another stack operation (y/n)? : ")


OUTPUT

Stack Operations
~~~~~~~~~~~~~~~~
1 - PUSH
2 - POP
3 - PEEK
4 - DISPLAY
~~~~~~~~~~~~~~~~
Enter your Choice : 1
Enter the element which you want to push : 30
Do you want to perform another stack operation (y/n)? : y

Stack Operations
~~~~~~~~~~~~~~~~
1 - PUSH
2 - POP
3 - PEEK
4 - DISPLAY
~~~~~~~~~~~~~~~~
Enter your Choice : 1
Enter the element which you want to push : 20
Do you want to perform another stack operation (y/n)? : y
Stack Operations
~~~~~~~~~~~~~~~~
1 - PUSH
2 - POP
3 - PEEK
4 - DISPLAY
~~~~~~~~~~~~~~~~
Enter your Choice : 3
The top most element of stack is : 20
Do you want to perform another stack operation (y/n)? : y
Stack Operations
~~~~~~~~~~~~~~~~
1 - PUSH
2 - POP
3 - PEEK
4 - DISPLAY
~~~~~~~~~~~~~~~~
Enter your Choice : 4
The stack elements are :
20
30
Do you want to perform another stack operation (y/n)? : n
15. EVALUATING A POSTFIX EXPRESSION

GIVEN PROBLEM:
Write a Python program to evaluate a postfix expression using stack.

AIM: To write a Python program to evaluate a postfix expression using stack.

SOURCE CODE:

def push(ele):
stack.append(ele)
try :
stack = []
exp = input("Enter the Postfix Expression : ")
for op in exp:
if op.isalnum()==1:
push(op)
if op in '+-*/':
a = int(stack.pop())
b = int(stack.pop())
if op == '+':
c=a+b
push(c)
elif op == '-':
c=a-b
push(c)
elif op == '*':
c=a*b
push(c)
else:
c=a/b
push(c)
else:
print("Result : ", stack.pop())
except:
print("Error in the expression")

OUTPUT:

Enter the Postfix Expression : 23*2*4+


Result : 16
16. CREATING DATABASE AND TABLE BY USING PYTHON-MYSQL

GIVEN PROBLEM:
Write a Program to integrate MYSQL with Python to create a Database for a school and a
Table for storing student details

AIM:
To Write a Program to integrate MYSQL with Python to create a Database for a school and
a Table for storing student details

SOURCE CODE:

import mysql.connector
try:
con=mysql.connector.connect(host='localhost',user='root',password='Admin@12345')
if con.is_connected():
cur=con.cursor()
cur.execute("CREATE DATABASE Schooldb")
print("The School database is created successfully")
cur.execute("use Schooldb")
cur.execute("CREATE TABLE STUDENT(SNO INT PRIMARY KEY, SNAME VARCHAR(20),
SMARK FLOAT)")
print("Table Created successfully")
con.close()
except Exception as Err:
print("Error is ", Err)

OUTPUT

The school database is created successfully


Table Created successfully
17. INSERTING, SEARCHING AND DISPLAYING RECORDS BY USING PYTHON-MYSQL

GIVEN PROBLEM:
Write a Program to integrate MYSQL with Python by inserting records into the student table
and displaying the records.

AIM: To write a Program to integrate MYSQL with Python by inserting records into the student
table and displaying the records.

SOURCE CODE:

import mysql.connector
con=mysql.connector.connect(host='localhost',username='root',password='Admin@12345',
database='Schooldb')
if con.is_connected():
cur=con.cursor()
opt='y'
while opt=='y':
print("Record Insertion")
print("~~~~~~ ~~~~~~~")
sno = int(input("Enter Student Number : "))
sname = input("Enter Student Name : ")
smark = int(input("Enter Student Mark : "))
query = "insert into student values ({},'{}',{})".format(sno,sname,smark)
cur.execute(query)
con.commit()
print("Record Stored Successfully")
opt = input("Do you want to add another student details (y/n) : ")

query = "select * from student";


cur.execute(query)
data = cur.fetchall()
for i in data:
print(i)

print("\nRecord Searching")
print("~~~~~~ ~~~~~~~~~")
no = int(input("Enter the Student No. to be searched : "))
query = "select * from student where sno = {}".format(no)
cur.execute(query)
data = cur.fetchone()
if data != None:
print(data)
print("Record Found")
else:
print("Record not Found")
con.close()
OUTPUT

Record Insertion
~~~~~~ ~~~~~~~
Enter Student Number : 1001
Enter Student Name : Arul
Enter Student Mark : 80
Record Stored Successfully
Do you want to add another student details (y/n) : y
Record Insertion
~~~~~~ ~~~~~~~
Enter Student Number : 1002
Enter Student Name : Bala
Enter Student Mark : 90
Record Stored Successfully
Do you want to add another student details (y/n) : y
Record Insertion
~~~~~~ ~~~~~~~
Enter Student Number : 1003
Enter Student Name : Abi
Enter Student Mark : 76
Record Stored Successfully
Do you want to add another student details (y/n) : n
(1001, 'Arul', 80.0)
(1002, 'Bala', 90.0)
(1003, 'Abi', 76.0)

Record Searching
~~~~~~ ~~~~~~~
Enter the Student No. to be searched : 1002
(1002, 'Bala', 90.0)
Record Found
18. SEARCHING, UPDATING AND DISPLAYING RECORDS BY USING PYTHON-MYSQL

GIVEN PROBLEM:
Write a Python Program to integrate MYSQL with Python by updating records to the student
table and displaying the records.

AIM: To Write a Python Program to integrate MYSQL with Python by updating records to the
student table and displaying the records.

SOURCE CODE:

import mysql.connector
con=mysql.connector.connect(host='localhost',username='root',password='Admin@12345',
database='Schooldb')
if con.is_connected():
cur=con.cursor()
cur.execute("select * from student")
data = cur.fetchall()
for i in data:
print(i)
print("Record Updation")
print("~~~~~~ ~~~~~~~~")
no = int(input("Enter the Student Number to be Updated : "))
query = "select * from student where sno = {}".format(no)
cur.execute(query)
data = cur.fetchone()
if data != None:
print(data)
mark = int(input("Enter the Mark to be updated : "))
query = "update student set smark = {} where sno = {}".format(mark,no)
cur.execute(query)
con.commit()
cur.execute("select * from student")
data = cur.fetchall()
for i in data:
print(i)
else:
print("Record not Found")
con.close()

OUTPUT:

((1001, 'Arul', 80.0)


(1002, 'Bala', 90.0)
(1003, 'Abi', 76.0)

Record Updation
~~~~~~ ~~~~~~~~
Enter the Student Number to be Updated : 1003
(1003, 'Abi', 76.0)
Enter the Mark to be updated : 69
(1001, 'Arul', 80.0)
(1002, 'Bala', 90.0)
(1003, 'Abi', 69.0)
19. DISPLAYING RECORDS BY USING PYTHON-MYSQL

GIVEN PROBLEM:
Write a program that displays all records fetched from student table of MySQL database
“schooldb” by using pymysql to connect database

AIM:
To write a program that displays all records fetched from student table of MySQL database
“schooldb” by using pymysql to connect database

SOURCE CODE:

import pymysql
try:
mycon =pymysql.connect(host ="localhost",
user="root",password="Admin@12345",database="schooldb")
cur = mycon.cursor()
cur.execute("select * from student")
data=cur.fetchall()
count=cur.rowcount
if count>0:
print(count, " rows found in the table ")
for row in data:
print(row)
mycon.close()
else:
print("No rows selected")
except Exception as Err:
print("Error is ",Err)

OUTPUT:

5 rows found in the table


(101, 'Ajay R', 82.3)
(102, 'Balaji K', 81.9)
(103, 'Ramrajan K', 90.6)
(104, 'Sugan M', 78.6)
(105, 'Ranjith J', 69.8)
20. SQL QUERY –CREATION, INSERTION AND DISPLAY

GIVEN PROBLEM-:
Write Queries for the following Questions based on the given Table.
Rollno Name Mark Dept DOA
1001 Arul 80 COMPUTER 1997-01-10
1002 Bala 90 HISTORY 1998-03-24
1003 Abi 69 TAMIL 1996-12-12
1004 Chandru 70 NULL 1999-07-01
1005 Deepa 84 COMPUTER 1997-09-05

AIM: To Write Queries for the following questions based on the given table.
(a) Write a Query to Create a new database in the name of “SCHOOL”
mysql> CREATE DATABASE SCHOOL;
(b) Write a Query to Open the database “SCHOOL”
mysql> USE SCHOOL;
(c) Write a Query to list all the existing database names
mysql> SHOW DATABASES;

(d) Write a Query to create the above table called “STUDENT”


mysql> CREATE TABLE STUDENT( Rollno int Primary key, Name varchar(20), Mark float,
Dept varchar(20), DOA date);
(e) Write a Query to view the structure of the table
mysql> DESC STUDENT;
(f) Write a Query to insert record as given in the table
mysql> insert into student values (1001, ‘Arul’, 80, ‘COMPUTER’, ‘1997-01-10’);
mysql> insert into student values (1002, ‘Bala’, 90, ‘HISTORY’, ‘1998-03-24’);
mysql> insert into student values (1003, ‘Abi’, 69, ‘TAMIL’, ‘1996-12-12’);
mysql> insert into student values (1004, ‘Chandru’, 70, NULL, ‘1999-07-01’);
mysql> insert into student values (1005, ‘Deepa’, 84, ‘COMPUTER’, ‘1997-09-05’);

(g) Write a Query to display all the details of the Student


mysql> SELECT * FROM STUDENT;
21. SQL QUERY – UPDATE AND DISPLAY

GIVEN PROBLEM:
Write Queries for the following Questions based on the given Table.
Rollno Name Mark Dept DOA
1001 Arul 80 COMPUTER 1997-01-10
1002 Bala 90 HISTORY 1998-03-24
1003 Abi 69 TAMIL 1996-12-12
1004 Chandru 70 NULL 1999-07-01
1005 Deepa 84 COMPUTER 1997-09-05

AIM: To Write Queries for the following questions based on the given table.
(a) Write a Query to select distinct Department from student table
mysql> SELECT DISTINCT(DEPT) FROM STUDENT;

(b) To show all information about students of COMPUTER Department


mysql> SELECT * FROM STUDENT WHERE DEPT = ‘COMPUTER’;

(c) Write a Query to display students whose mark is between 70 and 80


Mysql> SELECT * FROM STUDENT WHERE MARK BETWEEN 70 AND 90;
(d) Write a Query to display name of the students whose name is ending with ‘a’
mysql> SELECT * FROM STUDENT WHERE NAME LIKE ‘%a’

(e) Write a Query to display the Student who have the latest date of admission
mysql> SELECT * FROM STUDENT WHERE DOA LIKE (SELECT MAX(DOA) FROM
STUDENT;

(f) Write a Query to update Deepa mark to 100


mysql> UPDATE STUDENT SET MARK = 100 WHERE NAME LIKE ‘DEEPA’;
22. SQL QUERY - ALTER, DELETE AND DROP

GIVEN PROBLEM:

Write Queries for the following Questions based on the given Table.

Rollno Name Mark Dept DOA


1001 Arul 80 COMPUTER 1997-01-10
1002 Bala 90 HISTORY 1998-03-24
1003 Abi 69 TAMIL 1996-12-12
1004 Chandru 70 NULL 1999-07-01
1005 Deepa 84 COMPUTER 1997-09-05

AIM: To Write Queries for the following questions based on the given table.

(a) Write a Query to add a column Address to Student table


mysql> ALTER TABLE STUDENT ADD ADDRESS VARCHAR(20);

(b) Write a Query to display Average mark of COMPUTER Department


mysql> SELECT AVG(MARK) FROM STUDENT WHERE DEPT = ‘COMPUTER’;
(c) Write a Query to display the Student Names is Descending Oder
mysql> SELECT NAME FROM STUDENT ORDER BY NAME DESC;

(d) Write a Query to display the Department wise Maximum mark


mysql> SELECT DEPT, MAX(MARK) FROM STUDENT GROUP BY DEPT;

(e) Write a Query to delete the Student details whose Mark is less than 70
mysql> DELETE FROM STUDENT WHERE MARK < 70;

(f) Write a Query to delete Student table from Database.


mysql> DROP TABLE STUDENT;
23. SQL QUERY USING TWO TABLES ON STOCK DATA
GIVEN PROBLEM:
Write Queries for the following Questions based on the given Table.

TABLE: STOCK
INO INAME DCODE QTY UNITPRICE STOCKDATE
8001 DHOOR DHALL 101 200 195 2024-03-31
8009 RAJMA 109 300 55 2024-03-01
6009 BADAM 109 50 800 2024-07-05
8011 GROUNDNUT 101 80 130 2024-05-07
8013 WALNUT 201 15 400 2024-05-08
8015 DATES 201 36 250 2024-08-01
5977 PERK 202 500 10 2024-06-21
5978 KITKAT 202 600 15 2024-07-01

TABLE:DEALERS
DCODE DNAME
101 PANDURANGA AGENCIES
109 GURU AGENCIES
201 GRACE NUTS
202 INDIAN STOCKIEST
AIM: To Write Queries for the following questions based on the given table.

a)To display the total Unit price of all the products whose Dcode is 202

b) To display details of all products in the stock table in descending order of stock date.
c) To display maximum unit price of products for each dealer individually as per dcode from the
table stock

d) To display the Iname and Dname from table stock and dealers.
24. SQL QUERY USING TWO TABLES ON STUDENT DATA
GIVEN PROBLEM:
Write Queries for the following Questions based on the given Table.

TABLE: STUDENT

TABLE: MARK
AIM: To Write Queries for the following questions based on the tables

a) Write a query to display student name,sexamno, tamil, English, physics, chemistry,maths,


computer_science from table student and mark for test =1

select s.sname,s.sexamno,m.tamil,m.english,m.physics,m.chemistry,m.maths,
m.computer_science from student s,mark m where s.sexamno = m.sexamno and
m.test=1;

b) Write a query to display Test = 1 and 2 marks of ‘Deva N’


select * from mark where test in (1,2) and sexamno = (select sexamno from student
where sname='Deva N');

c) Display the students name and mark those secured more 80 marks in Computer Science in
test =2.

select sname from student where sexamno in (select sexamno from mark where
computer_science>80 and test=2);
d) Display Exam Number, Student Name, Gender, Father Name and Total of all subjects from the
table ‘student’ and ‘mark and for test=1 and Give appropriate label for columns
select s.sexamno as 'Exam Number',s.sname as 'Student Name',s.gender as
'Gender',s.sfathername as 'FatherName',
m.tamil+m.english+m.physics+m.chemistry+m.maths+m.computer_science as 'Total'
from student s,mark m where s.sexamno=m.sexamno and m.test=1 order by s.sexamno ;

You might also like