0% found this document useful (0 votes)
5 views52 pages

Class 12 Computer Science Project

The document includes an acknowledgment section expressing gratitude to a teacher, parents, and friends for support in completing a Computer Science project. It contains a certificate of completion for Aahil Ansari's project, along with an index of various Python programs covering topics like number theory, geometry, data analysis, file handling, and SQL operations. The document also provides detailed code examples for several programs, demonstrating practical applications of Python in solving mathematical and computational problems.

Uploaded by

zunairansari451
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)
5 views52 pages

Class 12 Computer Science Project

The document includes an acknowledgment section expressing gratitude to a teacher, parents, and friends for support in completing a Computer Science project. It contains a certificate of completion for Aahil Ansari's project, along with an index of various Python programs covering topics like number theory, geometry, data analysis, file handling, and SQL operations. The document also provides detailed code examples for several programs, demonstrating practical applications of Python in solving mathematical and computational problems.

Uploaded by

zunairansari451
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

Acknowledgement

I would like to express my sincere gratitude to my teacher, Mr. Karaj


Singh, for giving me the invaluable opportunity to work on this
wonderful project. This experience not only enhanced my research
skill but also broadened my knowledge by introducing me to many
new concept. I am truly thankful to him for his guidance and support.

I would also like to extend my heartfelt thanks to my parents and


friends for their constant support and encouragement, which played a
vital role in helping me to complete this project within the given time
frame.

1
CERTIFICATE

This is certify that Aahil Ansari of class 12th Science has prepared the
Computer Science Project. The report is the result of his efforts and
endeavours.

The report is found worthy of acceptance as final project report for


the subject Computer Science of class 12. He has prepared the report
under my guidance

Principal C.S Teacher


St. Joseph School Mr. Karaj Singh

2
INDEX

1. Content
 Python Programs
# Number Theory and
Algebra
[Link] number Checker
[Link] sequence generator
[Link]/LCM
[Link] Quadratic Equations
[Link]
[Link] addition and multication
[Link] conversion
[Link] checker
[Link] Arithmetic Calculator
[Link] Guessing Game
# Geometry &
Mensuration
[Link] and Perimeter of Rectangle
[Link] and Surface of Circle
[Link] between two points in a Plane
[Link] of a Line segment
[Link] Product of Vectors
[Link] Product of Vector
# Data Analysis &
Visualization
[Link] Mean, Median , Mode of a list
[Link] Standard Deviation and Variance
[Link] Regression
[Link] generator for a Data set
[Link] Simulator

3
[Link] sort
[Link] sort
[Link] Search on a sorted List
# File Handling &
Connectivity
[Link] numbers in a text file
[Link] numbers in a text file
[Link] of numbers in a text file
[Link] of numbers in a text file
[Link] numbers in a text file
# Stacks operations
[Link] postfix expression using stack
[Link] infix expression using stack
[Link] infix to postfix
[Link] a number using Stack
[Link] balanced parenthesis
[Link] prefix expression
#Python – SQL programs
[Link] SQLlite Database and Table
[Link] data into SQL Table
[Link] data in SQL Table
[Link] data from SQL Table
[Link] data from SQL Table

 MySQL
# Table Sales
Query 1: Calculate Total Sales Value for Each Product
Query 2: Find Total and Average Sales Across All Products
Query 3: Calculate Discounted Price for Each Product
Query 4: Find Region-wise Total Sales
Query 5: Identify Products with Sales Above Average

4
# Table Employee
Query 1: Calculate Total Salary After Adding Bonus
Query 2: Calculate Net Salary After Deducting Tax
Query 3: Find Average Salary Department-Wise
Query 4: Find Employees Earning Above Average Salary
Query 5: Calculate Annual Net Salary for Each Employee

5
PYTHON PROGRAMS
 Number Theory and Algebra
# Program Name: Prime Number Checker

# A prime number is a number greater than 1 that has no divisors other than 1
and itself.

# Taking input from the user

num = int(input("Enter a number: "))# Prime numbers are greater than 1

if num > 1:

# Check for factors

for i in range(2, num):

if num % i == 0:

print(num, "is not a prime number.")

break

else:

# This else belongs to the for loop, not the if

print(num, "is a prime number.")

else:

print(num, "is not a prime number (prime numbers are greater than 1).")

6
# Program Name: Fibonacci Sequence Generator

# The Fibonacci sequence is a series of numbers in which

# each number is the sum of the two preceding ones.

# Example: 0, 1, 1, 2, 3, 5, 8, 13, ...

# Taking input from the user

n = int(input("Enter the number of terms: "))

# First two terms of the Fibonacci sequence

a, b = 0, 1

print("Fibonacci Sequence:")

if n <= 0:

print("Please enter a positive integer.")

elif n == 1:

print(a)

else:

print(a, b, end=" ")

# Generate the sequence

for i in range(2, n):

c=a+b

print(c, end=" ")

# Update values

a=b

b=c

7
# Program Name: GCD and LCM Calculator

# GCD (Greatest Common Divisor) is the largest number that divides both
numbers.

# LCM (Least Common Multiple) is the smallest number that is a multiple of both
numbers.

# Taking input from the user

a = int(input("Enter the first number: "))

b = int(input("Enter the second number: "))

# Finding GCD using a loop

x, y = a, b

while y != 0:

x, y = y, x % y

gcd = x

# Finding LCM using the relation: LCM = (a * b) / GCD

lcm = (a * b) // gcd

# Displaying the results

print("Greatest Common Divisor (GCD):", gcd)

print("Least Common Multiple (LCM):", lcm)

8
# Program Name: Quadratic Equation Solver

# A quadratic equation is of the form: ax² + bx + c = 0

# The solutions (roots) are given by the formula:

# x = (-b ± √(b² - 4ac)) / 2a

import math # To use the square root function

# Taking input from the user

a = float(input("Enter coefficient a: "))

b = float(input("Enter coefficient b: "))

c = float(input("Enter coefficient c: "))

# Calculating the discriminant

D = b**2 - 4*a*c

# Checking the nature of the roots

if D > 0:

# Two real and distinct roots

root1 = (-b + [Link](D)) / (2*a)

root2 = (-b - [Link](D)) / (2*a)

print("Two real and distinct roots:")

print("Root 1 =", root1)

print("Root 2 =", root2)

elif D == 0:

# Two real and equal roots

root = -b / (2*a)

9
print("Two real and equal roots:")

print("Root =", root)

else:

# Complex roots

real_part = -b / (2*a)

imag_part = [Link](-D) / (2*a)

print("Complex roots:")

print("Root 1 =", real_part, "+", imag_part, "i")

print("Root 2 =", real_part, "-", imag_part, "i")

# Program Name: Factorial, Permutation, and Combination Calculator

# Formula:

# Factorial: n! = n × (n-1) × (n-2) × ... × 1

# Permutation: nPr = n! / (n - r)!

# Combination: nCr = n! / [r! × (n - r)!]

def factorial(n):

"""Function to calculate factorial of a number."""

fact = 1

for i in range(1, n + 1):

fact *= i

return fact

10
# Taking input from the user

n = int(input("Enter value of n: "))

r = int(input("Enter value of r: "))

# Checking if inputs are valid

if n < 0 or r < 0 or r > n:

print("Invalid input! Please ensure n ≥ r ≥ 0.")

else:

n_fact = factorial(n)

r_fact = factorial(r)

n_r_fact = factorial(n - r)

# Calculating permutation and combination

nPr = n_fact // n_r_fact

nCr = n_fact // (r_fact * n_r_fact)

# Displaying results

print("\nResults:")

print("Factorial of", n, "=", n_fact)

print("Permutation (nPr) =", nPr)

print("Combination (nCr) =", nCr)

11
# Program Name: Matrix Addition and Multiplication

# Matrix addition and multiplication are basic operations in mathematics.

# - In addition, corresponding elements are added.

# - In multiplication, rows of the first matrix are multiplied by columns of the


second matrix.

# Taking input for the first matrix

r1 = int(input("Enter number of rows in first matrix: "))

c1 = int(input("Enter number of columns in first matrix: "))

print("Enter elements of first matrix:")

A = []

for i in range(r1):

row = list(map(int, input().split()))

[Link](row)

# Taking input for the second matrix

r2 = int(input("Enter number of rows in second matrix: "))

c2 = int(input("Enter number of columns in second matrix: "))

print("Enter elements of second matrix:")

B = []

12
for i in range(r2):

row = list(map(int, input().split()))

[Link](row)

# -------- Matrix Addition --------

if r1 == r2 and c1 == c2:

print("\nMatrix Addition Result:")

for i in range(r1):

for j in range(c1):

print(A[i][j] + B[i][j], end=" ")

print()

else:

print("\nMatrix addition not possible! (Dimensions must be same)")

# -------- Matrix Multiplication --------

if c1 == r2:

print("\nMatrix Multiplication Result:")

# Initialize result matrix with zeros

result = [[0 for _ in range(c2)] for _ in range(r1)]

# Multiply matrices

for i in range(r1):

13
for j in range(c2):

for k in range(c1):

result[i][j] += A[i][k] * B[k][j]

# Display result

for row in result:

print(*row)

else:

print("\nMatrix multiplication not possible! (Columns of A must equal rows of


B)")

# Program Name: Base Conversion (Decimal to Binary, Octal, and Hexadecimal)

# A base conversion means changing a number from one base (like decimal)

# to another base system (like binary, octal, or hexadecimal).

# Taking input from the user

decimal = int(input("Enter a decimal number: "))

# Converting to different bases

binary = bin(decimal) # Converts to binary (prefix '0b')

octal = oct(decimal) # Converts to octal (prefix '0o')

hexa = hex(decimal) # Converts to hexadecimal (prefix '0x')

# Displaying the results

print("\nBase Conversion Results:")

print("Binary =", binary[2:]) # [2:] removes '0b' prefix

14
print("Octal =", octal[2:]) # [2:] removes '0o' prefix

print("Hexadecimal=", hexa[2:].upper()) # [2:] removes '0x' and makes letters


uppercase

# Program Name: Modular Arithmetic Calculator

# Modular arithmetic deals with remainders.

# Example: (a + b) mod n gives the remainder when (a + b) is divided by n.

# Taking input from the user

a = int(input("Enter first number (a): "))

b = int(input("Enter second number (b): "))

n = int(input("Enter modulus (n): "))

print("\nModular Arithmetic Results:")

# Addition under modulo

add_mod = (a + b) % n

print("(a + b) mod n =", add_mod)

# Subtraction under modulo

sub_mod = (a - b) % n

print("(a - b) mod n =", sub_mod)

# Multiplication under modulo

mul_mod = (a * b) % n

print("(a * b) mod n =", mul_mod)

15
# Division under modulo (only if b and n are coprime)

# For division, we multiply by modular inverse of b modulo n (if it exists)

try:

inv_b = pow(b, -1, n) # Python 3.8+ supports modular inverse with pow()

div_mod = (a * inv_b) % n

print("(a / b) mod n =", div_mod)

except ValueError:

print("(a / b) mod n is not possible (no modular inverse for b mod n).")

# Program Name: Number Guessing Game

# This program generates a random number and asks the user to guess it.

import random # To generate random numbers

# Generate a random number between 1 and 100

secret_number = [Link](1, 100)

print("Welcome to the Number Guessing Game!")

print("I have chosen a number between 1 and 100. Try to guess it!")

# Loop until the user guesses correctly

while True:

guess = int(input("Enter your guess: "))

if guess < secret_number:

print("Too low! Try again.")

elif guess > secret_number:

16
print("Too high! Try again.")

else:

print(" Congratulations! You guessed the number correctly!")

break

17
 Geometry and Mensuration
# Program Name: Rectangle Area and Perimeter Calculator

# The area of a rectangle = length × width

# The perimeter of a rectangle = 2 × (length + width)

# Taking input from the user

length = float(input("Enter the length of the rectangle: "))

width = float(input("Enter the width of the rectangle: "))

# Calculating area

area = length * width

# Calculating perimeter

perimeter = 2 * (length + width)

# Displaying the results

print("\nResults:")

print("Area of the rectangle =", area)

print("Perimeter of the rectangle =", perimeter)

18
# Program Name: Circle and Sphere Calculator

import math # To use pi and sqrt functions

# Circle calculations

radius = float(input("Enter the radius: "))

# Area of circle

circle_area = [Link] * radius**2

# Circumference of circle

circle_circumference = 2 * [Link] * radius

print("\nCircle:")

print("Area =", round(circle_area, 2))

print("Circumference =", round(circle_circumference, 2))

# Sphere calculations

# Volume of sphere = (4/3) * pi * r^3

# Surface area of sphere = 4 * pi * r^2

sphere_volume = (4/3) * [Link] * radius**3

sphere_surface_area = 4 * [Link] * radius**2

print("\nSphere:")

19
print("Volume =", round(sphere_volume, 2))

print("Surface Area =", round(sphere_surface_area, 2))

# Program: Distance Between Two Points in a Plane

# Importing the math module to use the square root function

import math

# Taking input from the user for the coordinates of the first point

x1 = float(input("Enter x-coordinate of first point: "))

y1 = float(input("Enter y-coordinate of first point: "))

# Taking input from the user for the coordinates of the second point

x2 = float(input("Enter x-coordinate of second point: "))

y2 = float(input("Enter y-coordinate of second point: "))

# Calculating the distance using the distance formula

# Distance formula: sqrt((x2 - x1)^2 + (y2 - y1)^2)

distance = [Link]((x2 - x1)**2 + (y2 - y1)**2)

# Displaying the result

print("The distance between the two points is:", distance)

20
# Program: Midpoint of a Line Segment

# Taking input from the user for the coordinates of the first point

x1 = float(input("Enter x-coordinate of first point: "))

y1 = float(input("Enter y-coordinate of first point: "))

# Taking input from the user for the coordinates of the second point

x2 = float(input("Enter x-coordinate of second point: "))

y2 = float(input("Enter y-coordinate of second point: "))

# Calculating the midpoint

# Midpoint formula: ((x1 + x2)/2 , (y1 + y2)/2)

mid_x = (x1 + x2) / 2

mid_y = (y1 + y2) / 2

# Displaying the result

print("The midpoint of the line segment is: (", mid_x, ",", mid_y, ")")

21
# Program: Cross Product of Two Vectors

import math

# Taking input for vector A

x1 = float(input("Enter x-component of vector A: "))

y1 = float(input("Enter y-component of vector A: "))

z1 = float(input("Enter z-component of vector A: "))

# Taking input for vector B

x2 = float(input("Enter x-component of vector B: "))

y2 = float(input("Enter y-component of vector B: "))

z2 = float(input("Enter z-component of vector B: "))

# Calculating cross product

# Cross product formula:

# A × B = (y1*z2 - z1*y2)i - (x1*z2 - z1*x2)j + (x1*y2 - y1*x2)k

cross_x = y1*z2 - z1*y2

cross_y = z1*x2 - x1*z2

cross_z = x1*y2 - y1*x2

q = [Link](cross_x**2 + cross_y**2 + cross_z**2)

# Displaying the result

print("The cross product of two vector is : ",q)

22
# Program: Dot Product of Two Vectors

# Taking input for vector A

x1 = float(input("Enter x-component of vector A: "))

y1 = float(input("Enter y-component of vector A: "))

z1 = float(input("Enter z-component of vector A: "))

# Taking input for vector B

x2 = float(input("Enter x-component of vector B: "))

y2 = float(input("Enter y-component of vector B: "))

z2 = float(input("Enter z-component of vector B: "))

# Calculating dot product

# Dot product formula: A · B = x1*x2 + y1*y2 + z1*z2

dot_product = x1*x2 + y1*y2 + z1*z2

# Displaying the result

print("The dot product of vectors A and B is:", dot_product)

23
 Data Analysis and Visualization

# Program: Mean, Median, and Mode of a List

# Importing the statistics module to use built-in functions

import statistics

# Taking input from the user as a list of numbers

numbers = list(map(float, input("Enter numbers separated by space: ").split()))

# Calculating mean

mean_value = [Link](numbers)

# Calculating median

median_value = [Link](numbers)

# Calculating mode

# Note: If there are multiple modes, [Link] will return the first one

try:

mode_value = [Link](numbers)

except [Link]:

mode_value = "No unique mode"

# Displaying the results

print("Mean:", mean_value)

print("Median:", median_value)

print("Mode:", mode_value)

24
# Program: Variance and Standard Deviation of a List

# Importing the statistics module

import statistics

# Taking input from the user as a list of numbers

numbers = list(map(float, input("Enter numbers separated by space: ").split()))

# Calculating variance

variance_value = [Link](numbers) # Sample variance

# Calculating standard deviation

std_deviation = [Link](numbers) # Sample standard deviation

# Displaying the results

print("Variance:", variance_value)

print("Standard Deviation:", std_deviation)

25
# Program: Simple Linear Regression

# Importing necessary library

import [Link] as plt

# Taking input for dataset

# Example format: x values: 1 2 3 4 5

x = list(map(float, input("Enter x values separated by space: ").split()))

y = list(map(float, input("Enter y values separated by space: ").split()))

# Check if both lists are of same length

if len(x) != len(y):

print("Error: x and y must have the same number of values.")

exit()

# Calculating mean of x and y

x_mean = sum(x) / len(x)

y_mean = sum(y) / len(y)

# Calculating slope (m) using formula: m = Σ((xi - x_mean)*(yi - y_mean)) / Σ((xi -


x_mean)^2)

numerator = sum((xi - x_mean)*(yi - y_mean) for xi, yi in zip(x, y))

denominator = sum((xi - x_mean)**2 for xi in x)

slope = numerator / denominator

# Calculating intercept (b) using formula: b = y_mean - m*x_mean

intercept = y_mean - slope * x_mean

26
# Displaying the linear regression equation

print(f"The linear regression equation is: y = {slope:.2f}x + {intercept:.2f}")

# Optional: Plotting the data points and regression line

[Link](x, y, color='blue', label='Data Points')

regression_line = [slope*xi + intercept for xi in x]

[Link](x, regression_line, color='red', label='Regression Line')

[Link]("x")

[Link]("y")

[Link]("Linear Regression")

[Link]()

[Link]()

# Program: Histogram Generator for a Data Set

pip install matplotlib,

# Importing the matplotlib library for plotting

import [Link] as plt

# Taking input from the user as a list of numbers

data = list(map(float, input("Enter numbers separated by space: ").split()))

# Asking the user for the number of bins (optional)

bins = int(input("Enter number of bins for the histogram: "))

27
# Creating the histogram

[Link](data, bins=bins, color='skyblue', edgecolor='black')

# Adding title and labels

[Link]("Histogram of the Data Set")

[Link]("Value")

[Link]("Frequency")

# Displaying the histogram

[Link]()

# Program: Probability Simulator (Coin Flip and Dice Roll)

# Importing the random module

import random

# Function to simulate coin flips

def coin_flip_simulation(flips):

results = {"Heads": 0, "Tails": 0}

for _ in range(flips):

result = [Link](["Heads", "Tails"])

results[result] += 1

return result

28
# Function to simulate dice rolls

def dice_roll_simulation(rolls):

results = {i: 0 for i in range(1, 7)}

for _ in range(rolls):

result = [Link](1, 6)

results[result] += 1

return results

# Main program

print("Probability Simulator")

choice = input("Enter 'coin' to flip a coin or 'dice' to roll a dice: ").lower()

if choice == "coin":

flips = int(input("Enter number of coin flips: "))

coin_results = coin_flip_simulation(flips)

print("Coin Flip Results:", coin_results)

elif choice == "dice":

rolls = int(input("Enter number of dice rolls: "))

dice_results = dice_roll_simulation(rolls)

print("Dice Roll Results:", dice_results)

else:

print("Invalid choice! Please enter 'coin' or 'dice'.")

29
# Program: Bubble Sort

# Taking input from the user

numbers = list(map(int, input("Enter numbers separated by space: ").split()))

# Bubble Sort Algorithm

n = len(numbers)

for i in range(n):

for j in range(0, n-i-1):

if numbers[j] > numbers[j+1]:

# Swap if the element found is greater than the next element

numbers[j], numbers[j+1] = numbers[j+1], numbers[j]

# Displaying the sorted list

print("Sorted list using Bubble Sort:", numbers)

# Program: Insertion Sort

# Taking input from the user

numbers = list(map(int, input("Enter numbers separated by space: ").split()))

# Insertion Sort Algorithm

for i in range(1, len(numbers)):

key = numbers[i]

j=i-1

# Move elements of numbers[0..i-1], that are greater than key, one position
ahead

while j >= 0 and numbers[j] > key:

30
numbers[j + 1] = numbers[j]

j -= 1

numbers[j + 1] = key

# Displaying the sorted list

print("Sorted list using Insertion Sort:", numbers)

# Program: Binary Search on a Sorted List

# Taking input for a sorted list

numbers = list(map(int, input("Enter a sorted list of numbers separated by space:


").split()))

# Taking input for the element to search

target = int(input("Enter the number to search: "))

# Binary Search Algorithm

low = 0

high = len(numbers) - 1

found = False

while low <= high:

mid = (low + high) // 2

if numbers[mid] == target:

found = True

break

elif numbers[mid] < target:

low = mid + 1

31
else:

high = mid - 1

# Displaying the result

if found:

print(f"{target} found at position {mid} (0-indexed).")

else:

print(f"{target} not found in the list.")

32
 File Handling and Connectivity

# Program: Write Numbers to a Text File

numbers = [10, 20, 30, 40, 50]

with open("[Link]", "w") as file:

for num in numbers:

[Link](str(num) + "\n")

print("Numbers written to [Link]")

# Program: Append Numbers to a Text File

more_numbers = [60, 70, 80]

with open("[Link]", "a") as file:

for num in more_numbers:

[Link](str(num) + "\n")

print("Numbers appended to [Link]")

# Program: Sum of Numbers from a Text File

with open("[Link]", "r") as file:

numbers = [float([Link]()) for line in file]

total = sum(numbers)

print("Sum of numbers:", total)

33
 Stack Operation

# Program: Evaluate Postfix Expression Using Stack (Mathematical Operations)

def evaluate_postfix(expression):

stack = []

for char in expression:

if [Link](): # If operand, push to stack

[Link](int(char))

else: # If operator, pop two operands and apply operator

b = [Link]()

a = [Link]()

if char == '+':

[Link](a + b)

elif char == '-':

[Link](a - b)

elif char == '*':

[Link](a * b)

elif char == '/':

[Link](a / b)

elif char == '^':

[Link](a ** b)

return stack[0] # Result will be at the top of stack

34
# Input postfix expression (e.g., "23*5+")

expr = input("Enter postfix expression (single-digit operands only): ")

result = evaluate_postfix(expr)

print("Result of expression:", result)

# Program : Evaluate Infix Expression Using Two Stacks

def precedence(op):

if op == '+' or op == '-':

return 1

if op == '*' or op == '/':

return 2

if op == '^':

return 3

return 0

def apply_op(a, b, op):

if op == '+': return a + b

if op == '-': return a - b

if op == '*': return a * b

if op == '/': return a / b

if op == '^': return a ** b

35
def evaluate(expression):

values = []

ops = []

i=0

while i < len(expression):

if expression[i] == ' ':

i += 1

continue

elif expression[i].isdigit():

val = 0

while i < len(expression) and expression[i].isdigit():

val = (val * 10) + int(expression[i])

i += 1

[Link](val)

elif expression[i] == '(':

[Link](expression[i])

i += 1

elif expression[i] == ')':

while ops and ops[-1] != '(':

val2 = [Link]()

val1 = [Link]()

36
op = [Link]()

[Link](apply_op(val1, val2, op))

[Link]()

i += 1

else:

while ops and precedence(ops[-1]) >= precedence(expression[i]):

val2 = [Link]()

val1 = [Link]()

op = [Link]()

[Link](apply_op(val1, val2, op))

[Link](expression[i])

i += 1

while ops:

val2 = [Link]()

val1 = [Link]()

op = [Link]()

[Link](apply_op(val1, val2, op))

return values[0]

expr = input("Enter infix expression: ")

print("Result:", evaluate(expr))

37
# Program : Convert Infix Expression to Postfix Using Stack

def precedence(op):

if op == '+' or op == '-': return 1

if op == '*' or op == '/': return 2

if op == '^': return 3

return 0

def infix_to_postfix(expression):

stack = []

output = ""

for char in expression:

if [Link]():

output += char

elif char == '(':

[Link](char)

elif char == ')':

while stack and stack[-1] != '(':

output += [Link]()

[Link]()

else:

while stack and precedence(stack[-1]) >= precedence(char):

output += [Link]()

38
[Link](char)

while stack:

output += [Link]()

return output

expr = input("Enter infix expression: ")

print("Postfix Expression:", infix_to_postfix(expr))

# Program : Reverse a Number Using Stack

def reverse_number(num):

stack = []

while num > 0:

[Link](num % 10)

num //= 10

reversed_num = 0

multiplier = 1

while stack:

reversed_num += [Link]() * multiplier

multiplier *= 10

return reversed_num

number = int(input("Enter a number: "))

print("Reversed number:", reverse_number(number))

39
# Program : Check Balanced Parentheses Using Stack

def is_balanced(expr):

stack = []

mapping = {')':'(', '}':'{', ']':'['}

for char in expr:

if char in '({[':

[Link](char)

elif char in ')}]':

if not stack or stack[-1] != mapping[char]:

return False

[Link]()

return len(stack) == 0

expression = input("Enter an expression with parentheses: ")

print("Balanced" if is_balanced(expression) else "Not Balanced")

# Program : Evaluate Prefix Expression Using Stack

def evaluate_prefix(expression):

stack = []

for char in expression[::-1]: # Read expression from right to left

if [Link]():

[Link](int(char))

40
else:

a = [Link]()

b = [Link]()

if char == '+': [Link](a + b)

elif char == '-': [Link](a - b)

elif char == '*': [Link](a * b)

elif char == '/': [Link](a / b)

elif char == '^': [Link](a ** b)

return stack[0]

expr = input("Enter prefix expression: ")

print("Result of expression:", evaluate_prefix(expr))

41
 Python –SQL programs

# Program: Create SQLite Database and Table

import sqlite3

conn = [Link]("[Link]")

cursor = [Link]()

[Link]("""CREATE TABLE IF NOT EXISTS students (

id INTEGER PRIMARY KEY,

name TEXT,

marks REAL

)""")

[Link]()

[Link]()

print("Database and table created successfully.")

42
# Program: Insert Data into SQLite Table

import sqlite3

conn = [Link]("[Link]")

cursor = [Link]()

students = [(1, "Alice", 85.5), (2, "Bob", 90.0), (3, "Charlie", 78.0)]

[Link]("INSERT INTO students VALUES (?, ?, ?)", students)

[Link]()

[Link]()

print("Data inserted successfully.")

# Program: Update Data in SQLite Table

import sqlite3

conn = [Link]("[Link]")

cursor = [Link]()

[Link]("UPDATE students SET marks = 95 WHERE name = 'Alice'")

[Link]()

[Link]()

print("Data updated successfully.")

43
# Program: Delete Data from SQLite Table

import sqlite3

conn = [Link]("[Link]")

cursor = [Link]()

[Link]("DELETE FROM students WHERE name = 'Charlie'")

[Link]()

[Link]()

print("Data deleted successfully.")

# Program: Read Data from SQLite Table

import sqlite3

conn = [Link]("[Link]")

cursor = [Link]()

[Link]("SELECT * FROM students")

rows = [Link]()

for row in rows:

print(row)

[Link]()

44
SQL QUERIES

 Creating a Sample Table 1


CREATE TABLE Sales (
ProductID INT PRIMARY KEY,
ProductName VARCHAR(50),
QuantitySold INT,
PricePerUnit DECIMAL(10,2),
DiscountPercent DECIMAL(5,2),
Region VARCHAR(30)
);
INSERT INTO Sales VALUES
(101, 'Laptop', 15, 55000, 10, 'North'),
(102, 'Smartphone', 30, 25000, 5, 'South'),
(103, 'Headphones', 40, 1500, 15, 'East'),
(104, 'Tablet', 20, 30000, 8, 'West'),
(105, 'Smartwatch', 25, 8000, 12, 'North'),
(106, 'Keyboard', 50, 1200, 5, 'East'),
(107, 'Monitor', 18, 12000, 10, 'South'),
(108, 'Speaker', 22, 5000, 7, 'West');
select * from sales;
ProductID ProductName QuantitySold PricePerUnit DiscountPercent Region

101 Laptop 15 55000 10 North

102 Smartphone 30 25000 5 South

103 Headphones 40 1500 15 East

104 Tablet 20 30000 8 West

105 Smartwatch 25 8000 12 North

106 Keyboard 50 1200 5 East

107 Monitor 18 12000 10 South

108 Speaker 22 5000 7 West

45
Query 1: Calculate Total Sales Value for Each Product

SELECT
ProductName,
QuantitySold * PricePerUnit AS TotalSales
FROM
Sales;

Query 2: Find Total and Average Sales Across All Products

SELECT
SUM(QuantitySold * PricePerUnit) AS TotalSales,
AVG(QuantitySold * PricePerUnit) AS AverageSales
FROM
Sales;

Query 3: Calculate Discounted Price for Each Product

SELECT
ProductName,
PricePerUnit,
DiscountPercent,
PricePerUnit - (PricePerUnit * DiscountPercent /
100) AS DiscountedPrice
FROM
Sales;

46
Query 4: Find Region-wise Total Sales

SELECT
Region,
SUM(QuantitySold * PricePerUnit) AS
RegionTotalSales
FROM
Sales
GROUP BY
Region;

Query 5: Identify Products with Sales Above Average

SELECT
ProductName,
(QuantitySold * PricePerUnit) AS TotalSales
FROM
Sales
WHERE
(QuantitySold * PricePerUnit) > (
SELECT AVG(QuantitySold * PricePerUnit) FROM
Sales
);

 Creating Sample Table 2


CREATE TABLE Employee (
EmpID INT PRIMARY KEY,
EmpName VARCHAR(50),
Department VARCHAR(30),
BasicSalary DECIMAL(10,2),
BonusPercent DECIMAL(5,2),
TaxPercent DECIMAL(5,2));
INSERT INTO Employee VALUES
(201, 'Amit Sharma', 'Sales', 45000, 10, 5),
(202, 'Neha Gupta', 'HR', 52000, 8, 6),
(203, 'Ravi Kumar', 'IT', 60000, 12, 8),
(204, 'Pooja Mehta', 'Finance', 55000, 9, 7),

47
(205, 'Ankit Verma', 'IT', 48000, 15, 5),
(206, 'Simran Kaur', 'Sales', 43000, 10, 6),
(207, 'Vivek Singh', 'Finance', 50000, 8, 7),
(208, 'Karan Patel', 'HR', 47000, 10, 5);

EmpID EmpName Department BasicSalary BonusPercent TaxPercent

201 Amit Sharma Sales 45000 10 5

202 Neha Gupta HR 52000 8 6

203 Ravi Kumar IT 60000 12 8

204 Pooja Mehta Finance 55000 9 7

205 Ankit Verma IT 48000 15 5

206 Simran Kaur Sales 43000 10 6

207 Vivek Singh Finance 50000 8 7

208 Karan Patel HR 47000 10 5

48
Query 1: Calculate Total Salary After Adding Bonus

SELECT
EmpName,
BasicSalary,
BonusPercent,
BasicSalary + (BasicSalary * BonusPercent / 100) AS
SalaryWithBonus
FROM
Employee;

Query 2: Calculate Net Salary After Deducting Tax

SELECT
EmpName,
BasicSalary,
TaxPercent,
BasicSalary - (BasicSalary * TaxPercent / 100) AS
NetSalary
FROM
Employee;

Query 3: Find Average Salary Department-Wise

SELECT
Department,
AVG(BasicSalary) AS AverageSalary
FROM
Employee
GROUP BY
Department;

49
Query 4: Find Employees Earning Above Average Salary

SELECT
EmpName,
BasicSalary
FROM
Employee
WHERE
BasicSalary > (SELECT AVG(BasicSalary) FROM
Employee);

Query 5: Calculate Annual Net Salary for Each Employee

SELECT
EmpName,
(BasicSalary + (BasicSalary * BonusPercent / 100) -
(BasicSalary * TaxPercent / 100)) * 12 AS
AnnualNetSalary
FROM
Employee;

50
Bibliography
[Link] Official Documentation
Python Software Foundation. “Python 3 Documentation.”
Available at: [Link]

[Link] Official Reference Manual


Oracle Corporation. “MySQL 8.0 Reference Manual.”
Available at: [Link]

[Link] Tutorials
Various creators. “Python Calculator Project and MySQL Data Analysis Tutorials.”
Available at: [Link]

[Link] Arora, “Computer Science with Python,” Dhanpat Rai & Co.

[Link] Notes & Teacher Guidance

51
52

You might also like