Q1: Write a python program to calculate areas of geometric figures like circle,
rectangle and
triangle.
code :
# Circle Area
radius = float(input("Enter the radius of a Circle: "))
print("Area of Circle:", 3.14 * radius ** 2)
# Rectangle Area
length = float(input("Enter the length of a Rectangle: "))
breadth = float(input("Enter the breadth of a Rectangle: "))
print("Area of Rectangle:", length * breadth)
# Triangle Area
base = float(input("Enter the base of a Triangle: "))
height = float(input("Enter the height of a Triangle: "))
print("Area of Triangle:", 0.5 * base * height)
q2: Write a Python program to calculate the gross salary of an employee. The
program should
prompt the user for the basic salary (BS) and then compute the dearness allowance
(DA) as
70% of BS, the travel allowance (TA) as 30% of BS, and the house rent allowance
(HRA) as
10% of BS. Finally, it should calculate the gross salary as the sum of BS, DA, TA, and
HRA
and display the result.
Code:
try:
BS=float(input("Enter the basic salary:"))
print("the dearness allowance is",0.7*BS)
print("the Travel allowance is",0.3*BS)
print("the Home rent allowance is",0.1*BS)
print("the gross salary of the employee is",BS+0.7*BS+0.3*BS+0.1*BS)
except:
ValueError
print("please enter valid input")
Q3: Write a Python program to explore basic arithmetic operations. The program
should prompt
the user to enter two numbers and then perform addition, subtraction, multiplication,
division, and modulus operations on those numbers. The results of each operation
should be displayed
to the user.
Code:
try:
a=float(input('Enter first no: '))
b=float(input('Enter Second no: '))
intdiv=a//b
print("the sum of two no. is:",a+b)
print("the sub of two no. is:",a-b)
print("the mul of two no. is:",a*b)
print("the div of two no. is:",a/b)
print("the mod of two no. is:",a%b)
print("the intdiv of two no. is:",intdiv)
except:
ValueError
print("Enter valid input")
Q4: Develop a Python program to manage a task list using lists and tuples,
including adding, removing, updating, and sorting task
Code:
tasks = [] # List to store tasks
def show_tasks():
"""Display all tasks."""
if not tasks:
print("\nNo tasks added yet.")
else:
print("\nTask List:")
for i, task in enumerate(tasks, start=1):
print(f"{i}. {task[0]} - Priority: {task[1]}")
def add_task():
"""Add a new task."""
name = input("Enter task name: ")
priority = input("Enter priority (1-5): ")
tasks.append((name, priority))
print("Task added!")
def remove_task():
"""Remove a task by name."""
name = input("Enter task name to remove: ")
for task in tasks:
if task[0] == name:
tasks.remove(task)
print("Task removed!")
return
print("Task not found.")
def sort_tasks():
"""Sort tasks by priority (ascending)."""
tasks.sort(key=lambda x: x[1])
print("Tasks sorted by priority!")
while True:
print("\nTask Manager")
print("1. Show Tasks")
print("2. Add Task")
print("3. Remove Task")
print("4. Sort Tasks")
print("5. Exit")
choice = input("Enter your choice: ")
if choice == "1":
show_tasks()
elif choice == "2":
add_task()
elif choice == "3":
remove_task()
elif choice == "4":
sort_tasks()
elif choice == "5":
print("Goodbye!")
break
else:
print("Invalid choice. Try again.")
Q5: reate a Python code to demonstrate the use of sets and perform set operations
(union, intersection, difference) to manage student enrollments in multiple courses /
appearing for
multiple entrance exams like CET, JEE, NEET etc.
Code:
# Student sets
CET_students = {"CET_Student1", "CET_Student2", "CET_Student3"}
JEE_students = {"JEE_Student1", "JEE_Student2"}
NEET_students = {"NEET_Student1"}
# Union - All students
all_students = CET_students.union(JEE_students, NEET_students)
print("After union (all students):")
print(all_students)
# Intersection - Common students between CET and JEE (change if needed)
common_students = CET_students.intersection(JEE_students)
print("After intersection (common students between CET and JEE):")
print(common_students)
# Difference - Only CET students
only_CET_students = CET_students.difference(JEE_students, NEET_students)
print("After difference (only CET students):")
print(only_CET_students)
# Sorting - Sorted list of all students
sorted_students = sorted(all_students)
print("After sorting (all students):")
print(sorted_students)
Q6: Write a Python program to create, update, and manipulate a dictionary of student
records, including their grades and attendance.
Code:
student_records = {}
# Function to add a student record
def add_student():
name = input("Enter student name: ").strip()
if name in student_records:
print("Student already exists!")
return
grade = input(f"Enter attendance percentage for {name}: ").strip()
student_records[name] = {"Grade": grade}
print(f"Record added for {name}.")
# Function to update a student's record
def update_student():
name = input("Enter student name to update: ").strip()
if name not in student_records:
print("Student not found!")
return
grade = input(f"Enter new grade for {name} (press Enter to keep
current): ").strip()
attendance = input(f"Enter new attendance for {name} (press Enter to
keep current): ").strip()
if grade:
student_records[name]["Grade"] = grade
if attendance:
student_records[name]["Attendance"] = attendance
print(f"Record updated for {name}.")
# Function to display all student records
def view_records():
if len(student_records) == 0:
print("No student records found.")
else:
for name, details in student_records.items():
print(f"{name}: {details}")
# Function to delete a student record
def delete_student():
name = input("Enter student name to delete: ").strip()
if name in student_records:
student_records.pop(name)
print(f"Record deleted for {name}.")
else:
print(f"Student not found!")
# Main menu function
def main():
print("Student Record Keeper")
while True:
print("\n1. Add Student")
print("2. Update Student")
print("3. View All Students")
print("4. Delete Student")
print("5. Exit")
choice = input("Choose an option (1-5): ").strip()
if choice == "1":
add_student()
elif choice == "2":
update_student()
elif choice == "3":
view_records()
elif choice == "4":
delete_student()
elif choice == "5":
print("Exiting program. Goodbye!")
break
# Call the main function
if __name__ == "__main__":
main()
Q7:Develop a Python program that takes a numerical input and identifies whether it is
even or
odd, utilizing conditional statements and loops.
Code:
# Even OR Odd
choice = int(input("Enter 1 to Start and 0 to Stop: "))
while choice == 1:
number = int(input("Enter a Number: "))
if number % 2 == 0:
print(number, "is an Even Number.")
else:
print(number, "is an Odd Number.")
choice = int(input("Enter 1 to Continue and 0 to Stop: "))
print("Program Ended.")
Q8: Design a Python program to compute the factorial of a given integer N.
Code:
num = int(input("Enter a number to calculate factorial: "))
fact = 1
for i in range(1, num + 1):
fact *= i
print("The factorial of", num, "is", fact)
Q9:Using function, write a Python program to analyze the input number is prime or
not.
code:
# Q(5.1)
num = int(input("Enter a number: "))
if num < 2:
if num == 0:
print("0 is NOT a Prime number.")
elif num == 1:
print("1 is NOT a Prime number.")
else:
print("Negative numbers are NOT Prime.")
else:
is_prime = True
for i in range(2, num):
if num % i == 0:
is_prime = False
break
if is_prime:
print(f"{num} is a Prime number.")
else:
print(f"{num} is NOT a Prime number.")
Q10:Implement a simple Python calculator that takes user input and performs basic
arithmetic
operations (addition, subtraction, multiplication, division) using functions.
Code:
# Q(5.2)
import pdb
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
try:
pdb.set_trace()
result = a / b
return result
except ZeroDivisionError:
return "Error! Division by zero."
except Exception as e:
return f"An error occurred: {e}"
def calculator():
while True:
print("\nSimple Calculator")
print("1. Addition (+)")
print("2. Subtraction (-)")
print("3. Multiplication (*)")
print("4. Division (/)")
print("5. Exit")
choice = input("Enter your choice (1-5): ")
if choice == "5":
print("Exiting calculator. Goodbye!")
break
if choice in ("1", "2", "3", "4"):
try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == "1":
print(f"Result: {num1} + {num2} = {add(num1, num2)}")
elif choice == "2":
print(f"Result: {num1} - {num2} = {subtract(num1,
num2)}")
elif choice == "3":
print(f"Result: {num1} * {num2} = {multiply(num1,
num2)}")
elif choice == "4":
print(f"Result: {num1} / {num2} = {divide(num1,
num2)}")
except ValueError:
print("Invalid input! Please enter numeric values.")
else:
print("Invalid choice! Please select a valid option.")
calculator()
Q 11:
import re
def find_words_by_length(filename, word_length):
try:
with open(filename, 'r') as file:
text = file.read()
# Using re to find words
words = re.findall(r'\b\w+\b', text)
# Filter words by specified length
matching_words = [word for word in words if len(word) ==
word_length]
if matching_words:
print(f"Words with length {word_length}:")
for word in matching_words:
print(word)
else:
print(f"No words found with length {word_length}.")
except FileNotFoundError:
print("Error: File not found.")
except Exception as e:
print(f"An error occurred: {e}")
def main():
filename = input("Enter the filename (with extension): ").strip()
try:
word_length = int(input("Enter the word length to search for: "))
find_words_by_length(filename, word_length)
except ValueError:
print("Invalid input! Please enter a valid number for word
length.")
if __name__ == "__main__":
main()
Q12:Write a Python program that takes two numbers as input and performs division.
Implement
exception handling to manage division by zero and invalid input errors gracefully.
Code:
# exp 7.1
try:
# Taking input and converting to float
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
#Performing division
result = num1 / num2
print("Result:", result)
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
except ValueError:
print(" Error: Please Enter valid numbers")
print("Program completed.")
Q13:Write a Python script that prompts the user to enter their phone number and
email ID. It then
employs Regular Expressions to verify if these inputs adhere to standard phone
number and
email address formats
Code:
import re
# Get user input
phone = input("Enter your phone number: ")
email = input("Enter your email ID: ")
# Define simple regex patterns
phone_pattern = r'^\d{10}$' # Exactly 10 digits
email_pattern = r'^[\w\.-]+@[\w\.-]+\.\w+$' # Basic email format
# Validate phone number
if re.match(phone_pattern, phone):
print("Phone number is valid.")
else:
print("Invalid phone number. It should have exactly 10 digits.")
# Validate email address
if re.match(email_pattern, email):
print("Email ID is valid.")
else:
print("Invalid email ID.")
Q14: Create a program that reads a text file containing various data (e.g., names,
emails, phone
numbers). Use regular expressions to extract specifictypes of data, such as email
addresses, phone numbers, dates (e.g., MM/DD/YYYY format).
Code:
import re
# Read file content
filename = input("Enter the filename: ")
try:
with open(filename, 'r') as file:
text = file.read()
# Patterns
email_pattern = r'[\w\.-]+@[\w\.-]+\.\w+'
phone_pattern = r'\b\d{10}\b' # 10-digit phone numbers
date_pattern = r'\b\d{2}/\d{2}/\d{4}\b' # MM/DD/YYYY format
# Find all matches
emails = re.findall(email_pattern, text)
phones = re.findall(phone_pattern, text)
dates = re.findall(date_pattern, text)
# Print results
print("\nEmails found:", emails)
print("Phone numbers found:", phones)
print("Dates found:", dates)
except FileNotFoundError:
print("Error: File not found.")
Q15: Develop a Python script to create two arrays of the same shape and perform
element-wise
addition, subtraction, multiplication, and division. Calculate the dot product and cross
product
of two vectors.
Code:
import numpy as np
# Create two arrays
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
# Element-wise operations
print("Addition:", a + b)
print("Subtraction:", a - b)
print("Multiplication:", a * b)
print("Division:", a / b)
# Dot product
print("Dot Product:", np.dot(a, b))
# Cross product
print("Cross Product:", np.cross(a, b))