0% found this document useful (0 votes)
7 views39 pages

Index

The document is a practical file submitted by S. Roshan Kumar, a student of class XII B, containing various programming projects and exercises. Each section includes a specific task, such as calculating roots of quadratic equations, currency conversion, character counting, and games like 'Guess a Number' and 'Stone, Paper, and Scissors'. The document showcases the implementation of these tasks using Python code, emphasizing user interaction and error handling.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views39 pages

Index

The document is a practical file submitted by S. Roshan Kumar, a student of class XII B, containing various programming projects and exercises. Each section includes a specific task, such as calculating roots of quadratic equations, currency conversion, character counting, and games like 'Guess a Number' and 'Stone, Paper, and Scissors'. The document showcases the implementation of these tasks using Python code, emphasizing user interaction and error handling.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 39

P M SHRI KENDRIYA VIDYALAYA

ANNA NAGAR CH- 40

Practical file

SUBMITTED BY: -
Name: S. Roshan Kumar
Class & Section: XII B
Session :2024-25
INDEX
Roots of a Quadratic Equation
1.
Currency Conversion
2.
Math Module Remake
3.
Character Counting
4.
GCD and LCM Calculator
5.
Temperature Conversions
6.
Password Strength Check
7.
Student Compare
8.
Decimal to Binary Conversion
9.
Sequence Counter
10.
Student Details Data Handling
11.
Guess a Number! Game
12.
GST Rate Calculator
13.
14. Stone, Paper, and Scissors! Game

Stack Operation on List


15.
Employees Database
16.
Expense Management System
17.
Students Database
18.
Adding and Remove Student Database
19.
Employee Payroll Management System
20.
Roots of a Quadratic Equation
A program to find the roots of a quadratic
equation using the quadratic formula.
import cmath
def find_roots(a, b, c):
d = (b**2) - (4*a*c)
root1 = (-b + cmath.sqrt(d)) / (2 * a)
root2 = (-b - cmath.sqrt(d)) / (2 * a)
return root1, root2
# Enhanced with user input and display formatting
def main():
try:
a = float(input("Enter coefficient a: "))
b = float(input("Enter coefficient b: "))
c = float(input("Enter coefficient c: "))
if a == 0:
print("Coefficient 'a' cannot be zero in a quadratic
equation.")
else:
root1, root2 = find_roots(a, b, c)
print(f"The roots of the equation are: {root1} and
{root2}")
except ValueError:
print("Please enter valid numeric values.")

main()

Currency Conversion
Convert between different currencies based on
current exchange rates.
conversion_rates = { "USD": {"INR": 74.5, "EUR": 0.85, "JPY":
110},"INR": {"USD": 0.013, "EUR": 0.011, "JPY": 1.47} }
def currency_conversion(amount, from_currency, to_currency):
if from_currency in conversion_rates and to_currency in
conversion_rates[from_currency]:
return amount * conversion_rates[from_currency]
[to_currency]
else:
return None
# Enhanced with user interaction
def main():
try:
amount = float(input("Enter amount: "))
from_currency = input("From currency (USD, INR, EUR, JPY):
").upper()

to_currency = input("To currency (USD, INR, EUR, JPY):


").upper()
result = currency_conversion(amount, from_currency,
to_currency)
if result is not None:
print(f"{amount} {from_currency} = {result:.2f}
{to_currency}")
else:
print("Conversion rate not available for the selected
currencies.")
except ValueError:
print("Please enter a valid amount.")
main()

output for the first code:-

output for the second code:-


Math Module Remake

A custom implementation of common math


functions such as square root, power, etc.
import math

def custom_square_root(x):
return x ** 0.5

def custom_power(base, exponent):


return base ** exponent

def custom_log(x, base=math.e):


return math.log(x, base)

# Enhanced with more functions and user interaction


def main():
print("Select an operation:")
print("1. Square root")
print("2. Power")
print("3. Logarithm")

choice = input("Enter choice (1/2/3): ")


try:
if choice == '1':
x = float(input("Enter number: "))
print("Square root:", custom_square_root(x))
elif choice == '2':
base = float(input("Enter base: "))
exponent = float(input("Enter exponent: "))
print("Power:", custom_power(base, exponent))
elif choice == '3':
x = float(input("Enter number: "))
base = float(input("Enter base (default is e): ") or
math.e)
print("Logarithm:", custom_log(x, base))
else:
print("Invalid choice.")
except ValueError:
print("Please enter valid numeric values.")

main()

Character Counting
Count the number of characters, words, and
sentences in a given text.
def character_count(text):
# Initialize counters
char_count = len(text)
word_count = len(text.split())
line_count = text.count('\n') + 1 if text else 0
vowel_count = sum(1 for char in text if char.lower() in
'aeiou')
consonant_count = sum(1 for char in text if char.isalpha()
and char.lower() not in 'aeiou')
digit_count = sum(1 for char in text if char.isdigit())
space_count = text.count(' ')
sentence_count = sum(text.count(punct) for punct in ['.', '!',
'?'])

# Display results
print(f"Total Characters (including spaces): {char_count}")
print(f"Total Words: {word_count}")
print(f"Total Lines: {line_count}")
print(f"Total Vowels: {vowel_count}")
print(f"Total Consonants: {consonant_count}")
print(f"Total Digits: {digit_count}")
print(f"Total Spaces: {space_count}")
print(f"Total Sentences: {sentence_count}")
# Enhanced with interactive input and error handling
def main():
print("Character Counting Program")
print("==========================")
try:
text = input("Enter your text (press Enter to end input):\
n")
if not text:
print("No input provided.")
else:
character_count(text)
except Exception as e:
print(f"An error occurred: {e}")

# Run the main function


main()

GCD and LCM Calculator


Calculate the Greatest Common Divisor (GCD)
and Least Common Multiple (LCM) of two
numbers.
import math
from functools import reduce
def calculate_gcd(numbers):
"""Calculate GCD of a list of numbers using the math.gcd and
reduce functions."""
return reduce(math.gcd, numbers)
def calculate_lcm(numbers):
"""Calculate LCM of a list of numbers."""
def lcm(a, b):
return abs(a * b) // math.gcd(a, b)
return reduce(lcm, numbers)
def main():
print("Welcome to the GCD and LCM Calculator!")

print("==================================
=====")
print("1. Calculate GCD")
print("2. Calculate LCM")
print("3. Calculate both GCD and LCM")
try:
choice = input("Enter your choice (1/2/3): ")
if choice not in ['1', '2', '3']:
print("Invalid choice. Please enter 1, 2, or 3.")
return
numbers = input("Enter numbers separated by spaces:
").split()
numbers = [int(num) for num in numbers]
if choice == '1':
gcd_result = calculate_gcd(numbers)
print(f"The GCD of {numbers} is: {gcd_result}")

elif choice == '2':


lcm_result = calculate_lcm(numbers)
print(f"The LCM of {numbers} is: {lcm_result}")
elif choice == '3':
gcd_result = calculate_gcd(numbers)
lcm_result = calculate_lcm(numbers)
print(f"The GCD of {numbers} is: {gcd_result}")
print(f"The LCM of {numbers} is: {lcm_result}")
except ValueError:
print("Please enter valid integers separated by spaces.")
except Exception as e:
print(f"An error occurred: {e}")
main()
Temperature Conversions

Convert temperatures between Celsius,


Fahrenheit, and Kelvin
def celsius_to_fahrenheit(c):
return (c * 9/5) + 32

def fahrenheit_to_celsius(f):
return (f - 32) * 5/9

def celsius_to_kelvin(c):
return c + 273.15

def kelvin_to_celsius(k):
return k - 273.15

# Enhanced with interactive options


def main():
print("Choose conversion type:")
print("1. Celsius to Fahrenheit")
print("2. Fahrenheit to Celsius")
print("3. Celsius to Kelvin")
print("4. Kelvin to Celsius")

choice = input("Enter choice (1/2/3/4): ")


try:
if choice == '1':
c = float(input("Enter temperature in Celsius: "))
print("Fahrenheit:", celsius_to_fahrenheit(c))
elif choice == '2':
f = float(input("Enter temperature in Fahrenheit: "))
print("Celsius:", fahrenheit_to_celsius(f))
elif choice == '3':
c = float(input("Enter temperature in Celsius: "))
print("Kelvin:", celsius_to_kelvin(c))
elif choice == '4':
k = float(input("Enter temperature in Kelvin: "))
print("Celsius:", kelvin_to_celsius(k))
else:
print("Invalid choice.")
except ValueError:
print("Please enter a valid temperature.")

main()

Password Strength Check


Analyze the strength of a password based on
length, characters used, etc.
import re

def check_password_strength(password):
length = len(password) >= 8
upper = re.search(r'[A-Z]', password)
lower = re.search(r'[a-z]', password)
digit = re.search(r'[0-9]', password)
special = re.search(r'[@$!%*?&]', password)
if length and upper and lower and digit and special:
return "Strong Password"
else:
return "Weak Password"

# Example usage:
print(check_password_strength("P@ssw0rd"))

Student compare
Compare the details (such as grades) of two or
more students.
class Student:
def __init__(self, name, math, science, english):
self.name = name
self.average = (math + science + english) / 3

def input_student():
name = input("Enter student's name: ")
math = float(input("Enter Math grade: "))
science = float(input("Enter Science grade: "))
english = float(input("Enter English grade: "))
return Student(name, math, science, english)

def compare_students(student1, student2):


print(f"\n{student1.name}'s average:
{student1.average:.2f}")
print(f"{student2.name}'s average: {student2.average:.2f}")
if student1.average > student2.average:
print(f"{student1.name} has a higher average.")
elif student1.average < student2.average:
print(f"{student2.name} has a higher average.")
else:
print("Both students have the same average.")

# Main code
print("Enter details for Student 1:")
student1 = input_student()
print("\nEnter details for Student 2:")
student2 = input_student()
compare_students(student1, student2)

Decimal to Binary
Conversion
Convert a decimal number to its binary
equivalent.
def decimal_to_binary(decimal):
"""Convert a decimal number to binary."""
if decimal < 0:
return '-' + bin(decimal)[3:] # Handling negative numbers
else:
return bin(decimal)[2:] # Convert and strip '0b' prefix

def main():
print("Decimal to Binary Converter")
print("===========================")

while True:
try:
# Take input from the user
decimal = int(input("\nEnter a decimal number (or 'q' to
quit): "))

# Convert to binary and display the result


binary = decimal_to_binary(decimal)
print(f"The binary representation of {decimal} is:
{binary}")

except ValueError:
print("Please enter a valid integer or 'q' to quit.")
# Check if the user wants to continue
cont = input("Would you like to convert another number?
(y/n): ")
if cont.lower() != 'y':
print("Thank you for using the Decimal to Binary
Converter!")
break

# Run the main function


main()
Sequence Counter

Count specific sequences or patterns in a given


string or list.
def add_student(student_list):
"""Prompt the user to enter a student's name and add to the
list if unique."""
name = input("Enter student's name: ").strip()

if name in student_list:
print(f"{name} is already in the list.")
else:
student_list.append(name)
print(f"{name} has been added.")

def main():
print("Student Counter Program")
print("========================")

student_list = []

while True:
add_student(student_list)

cont = input("Would you like to add another student?


(y/n): ").strip().lower()
if cont != 'y':
break

# Display total count and all student names


print("\nStudent Entry Summary")
print("=======================")
print(f"Total unique students: {len(student_list)}")
print("List of students:")
for student in student_list:
print(f"- {student}")

# Run the main function


main()

Student Details Data


Handling
Handle and display detailed student information,
possibly with file storage.
class Student:
def __init__(self, name, age, grade, subjects):
self.name, self.age, self.grade = name, age, grade
self.subjects = [s.strip() for s in subjects.split(',')]
def __str__(self):
return f"{self.name} | Age: {self.age}, Grade:
{self.grade}, Subjects: {', '.join(self.subjects)}"

def add_student(students):
name = input("Name: ").strip()
age = int(input("Age: "))
grade = input("Grade: ")
subjects = input("Subjects (comma-separated): ")
students[name.lower()] = Student(name, age, grade,
subjects)

def view_student(students):
name = input("Enter name to view: ").strip().lower()
print(students.get(name, "Student not found."))

def list_students(students):
for student in students.values(): print(student)
print(f"Total: {len(students)}")

students = {}
while True:
option = input("\n1. Add 2. View 3. List 4. Exit\nChoose: ")
if option == '1': add_student(students)
elif option == '2': view_student(students)
elif option == '3': list_students(students)
elif option == '4': break

Guess a Number! Game


A simple guessing game where the player tries to
guess a randomly generated number.
import random

def play_game():
print("Welcome to the Guess a Number Game!")
level = int(input("Choose difficulty - 1: Easy (1-10), 2:
Medium (1-50), 3: Hard (1-100): "))
range_limit, max_attempts = [(10, 5), (50, 7), (100, 10)]
[level - 1]

target = random.randint(1, range_limit)


for attempt in range(1, max_attempts + 1):
guess = int(input(f"Attempt {attempt}/{max_attempts}:
Guess the number (1-{range_limit}): "))
if guess == target:
print(f"Correct! You guessed it in {attempt} attempts.\
n")
return
print("Too low!" if guess < target else "Too high!")

print(f"Out of attempts! The number was {target}.")


while input("\nPlay a round? (y/n): ").strip().lower() == 'y':
play_game()
print("Thanks for playing!")
GST Rate Calculator

Calculate the GST (Goods and Services Tax) for a


given amount.
# Function to calculate GST
def calculate_gst(amount, gst_rate):
gst_amount = (amount * gst_rate) / 100
total_amount = amount + gst_amount
return gst_amount, total_amount

# Input amount and GST rate


amount = float(input("Enter the amount: "))
gst_rate = float(input("Enter the GST rate (in %): "))

# Calculate GST
gst_amount, total_amount = calculate_gst(amount, gst_rate)

# Output the result


print(f"\nGST Amount: {gst_amount:.2f}")
print(f"Total Amount (Including GST): {total_amount:.2f}")

Stone, Paper, and Scissors!


Game
A game of rock-paper-scissors between the user
and the computer.
import random
def play_game():
choices = ["stone", "paper", "scissors"]
user_choice = input("Enter your choice (stone, paper, or
scissors): ").lower()
while user_choice not in choices:
user_choice = input("Invalid choice. Try again: ").lower()
computer_choice = random.choice(choices)
print(f"Computer chooses: {computer_choice}")
if user_choice == computer_choice:
return "It's a tie!"
elif (user_choice == "stone" and computer_choice ==
"scissors") or \
(user_choice == "scissors" and computer_choice ==
"paper") or \
(user_choice == "paper" and computer_choice ==
"stone"):
return "You win!"
else:
return "Computer wins!"
print(play_game())

Stack Operation on List

Implement stack operations (push, pop, peek) on


a list.
def push(stack, item):
stack.append(item)
print(f"{item} pushed to stack.")

def pop(stack):
print(f"{stack.pop() if stack else 'Stack is empty! Cannot
pop.'}")

def peek(stack):
print(f"Top of stack: {stack[-1] if stack else 'Stack is
empty!'}")

def display(stack):
print(f"Stack contents: {stack if stack else 'Stack is
empty!'}")

def main():
stack = []
print("Stack Operations: 1.Push 2.Pop 3.Peek 4.Display
5.Exit")
while True:
choice = input("Enter choice (1-5): ")
if choice == '1':
push(stack, input("Enter item to push: "))
elif choice == '2':
pop(stack)
elif choice == '3':
peek(stack)
elif choice == '4':
display(stack)
elif choice == '5':
print("Exiting..."); break
else:
print("Invalid choice!")

main()
Employees Database
A database to store and manage employee
details, such as name, position, and salary.
def main():
employees = {}
while True:
choice = input("1.Add 2.Search 3.Delete 4.Display 5.Exit:
")
if choice == '1':
emp_id = input("ID: "); name = input("Name: "); des =
input("Designation: ")
employees[emp_id] = {'Name': name, 'Designation':
des}
elif choice == '2':
emp_id = input("Search ID: ")
print(employees.get(emp_id, "Not Found"))
elif choice == '3':
emp_id = input("Delete ID: ")
print("Deleted" if employees.pop(emp_id, None) else
"Not Found")
elif choice == '4':
for emp_id, info in employees.items():
print(f"ID: {emp_id}, Name: {info['Name']},
Designation: {info['Designation']}")
elif choice == '5': break

main()
Expense Management
System
Track and manage expenses with options to add,
view, and categorize expenses.
def add_expense(expenses):
name = input("Enter Expense Name: ")
amount = float(input("Enter Amount: "))
expenses.append({'Name': name, 'Amount': amount})
print(f"Expense '{name}' added.")

def view_expenses(expenses):
if expenses:
print("\nExpenses:")
for exp in expenses:
print(f"{exp['Name']}: ₹{exp['Amount']}")
else:
print("No expenses recorded yet.")

def main():
expenses = []
print("Expense Management System")
while True:
choice = input("1. Add Expense 2. View Expenses 3. Exit:
")
if choice == '1':
add_expense(expenses)
elif choice == '2':
view_expenses(expenses)
elif choice == '3':
print("Exiting system.")
break
else:
print("Invalid choice! Please select a valid option.")

main()

output for the first code:-

output for the second code:-


Students Database

Add, remove, and manage student records in a


database.
def add_student(students):
student_id = input("Enter Student ID: ")
name = input("Enter Student Name: ")
students[student_id] = name
print(f"Student '{name}' added.")

def view_students(students):
if students:
print("\nStudent List:")
for student_id, name in students.items():
print(f"ID: {student_id}, Name: {name}")
else:
print("No students recorded yet.")

def main():
students = {}
print("Student Database System")
while True:
choice = input("1. Add Student 2. View Students 3. Exit: ")
if choice == '1':
add_student(students)
elif choice == '2':
view_students(students)
elif choice == '3':
print("Exiting system.")
break
else:
print("Invalid choice! Please select a valid option.")

main()
Adding and Remove
Student Database
Add, remove, and manage student records in a
database.
def add_student(students):
student_id = input("Enter Student ID: ")
name = input("Enter Student Name: ")
students[student_id] = name
print(f"Student '{name}' added.")

def remove_student(students):
student_id = input("Enter Student ID to remove: ")
if student_id in students:
del students[student_id]
print(f"Student with ID {student_id} removed.")
else:
print(f"Student with ID {student_id} not found.")

def view_students(students):
if students:
print("\nStudent List:")
for student_id, name in students.items():
print(f"ID: {student_id}, Name: {name}")
else:
print("No students recorded yet.")

def main():
students = {}
print("Student Database Management")
while True:
choice = input("1. Add Student 2. Remove Student 3. View
Students 4. Exit: ")
if choice == '1':
add_student(students)
elif choice == '2':
remove_student(students)
elif choice == '3':
view_students(students)
elif choice == '4':
print("Exiting system.")
break
else:
print("Invalid choice! Please select a valid option.")

main()

Employee Payroll
Management System
Calculate and manage employee payroll details,
including salary, deductions, and net pay.
def add_employee(employees):
emp_id = input("Enter Employee ID: ")
name = input("Enter Employee Name: ")
salary = float(input("Enter Salary: "))
employees[emp_id] = {'Name': name, 'Salary': salary}
print(f"Employee '{name}' added.")
def view_employees(employees):
if employees:
print("\nEmployee List:")
for emp_id, details in employees.items():
print(f"ID: {emp_id}, Name: {details['Name']}, Salary: ₹
{details['Salary']}")
else:
print("No employees recorded yet.")
def update_salary(employees):
emp_id = input("Enter Employee ID to update salary: ")
if emp_id in employees:
new_salary = float(input("Enter new salary: "))
employees[emp_id]['Salary'] = new_salary
print(f"Salary updated for employee {emp_id}.")
else:
print(f"Employee with ID {emp_id} not found.")
def main():
employees = {}
print("Employee Payroll Management System")
while True:
choice = input("1. Add Employee 2. View Employees 3.
Update Salary 4. Exit: ")
if choice == '1':
add_employee(employees)
elif choice == '2':
view_employees(employees)
elif choice == '3':
update_salary(employees)
elif choice == '4':
print("Exiting system.")
break
else:
print("Invalid choice! Please select a valid option.")
main()

You might also like