0% found this document useful (0 votes)
14 views18 pages

All Programs Updated

The document contains various Python programming exercises demonstrating different concepts such as personalized greetings, area calculations, salary computations, arithmetic operations, list and tuple manipulations, set operations, student records management, and error handling. Each exercise includes code snippets along with sample input and output to illustrate the functionality. The exercises cover a range of topics from basic input/output to more complex data structures and error management.

Uploaded by

wifeoftaehyungs
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)
14 views18 pages

All Programs Updated

The document contains various Python programming exercises demonstrating different concepts such as personalized greetings, area calculations, salary computations, arithmetic operations, list and tuple manipulations, set operations, student records management, and error handling. Each exercise includes code snippets along with sample input and output to illustrate the functionality. The exercises cover a range of topics from basic input/output to more complex data structures and error management.

Uploaded by

wifeoftaehyungs
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/ 18

Exp 1_1

# Personalized Greeting Generator


# Prompt the user for their name

name = input("Enter your name: ")

# Prompt the user for their preferred greeting style


greeting = input("Choose a greeting style (e.g., Hello, Hi, Good day): ")
# Combine the inputs into a personalized message

personalized_message = f"{greeting}, {name}!"


# Display the personalized message
print(personalized_message)

print(f"{greeting},{name} how are you?")


print(f"{name} say {greeting}")

OUTPUT:
Enter your name: Priya
Choose a greeting style (e.g., Hello, Hi, Good day): Hello
Hello, Priya!
Hello,Priya how are you?
Priya say Hello
Exp 1_2

# Program to calculate areas of geometric figures


print("Select a geometric figure: Circle, Rectangle, Triangle")
choice = input("Your choice: ").strip().lower()

if choice == "circle":
radius = float(input("Enter the radius of the circle: "))
area = 3.14159 * radius ** 2
print(f"The area of the circle is {area:.2f}")

elif choice == "rectangle":


length = float(input("Enter the length of the rectangle: "))
width = float(input("Enter the width of the rectangle: "))
area = length * width
print(f"The area of the rectangle is {area:.2f}")

elif choice == "triangle":


base = float(input("Enter the base of the triangle: "))
height = float(input("Enter the height of the triangle: "))
area = 0.5 * base * height
print(f"The area of the triangle is {area:.2f}")

else:
print("Invalid choice! Please run the program again.")

OUTPUT:
Select a geometric figure: Circle, Rectangle, Triangle
Your choice: Circle
Enter the radius of the circle: 5
The area of the circle is 78.54

Select a geometric figure: Circle, Rectangle, Triangle


Your choice: Rectangle
Enter the length of the rectangle: 5
Enter the width of the rectangle: 6
The area of the rectangle is 30.00
Exp 2_1

# Program to calculate the gross salary of an employee

# Prompt user to enter the basic salary


basic_salary = float(input("Enter the Basic Salary (BS): "))

# Calculate allowances
da = 0.7 * basic_salary # Dearness Allowance
ta = 0.3 * basic_salary # Travel Allowance
hra = 0.1 * basic_salary # House Rent Allowance

# Calculate gross salary


gross_salary = basic_salary + da + ta + hra

# Display the gross salary


print(f"The Gross Salary is: {gross_salary:.2f}")

OUTPUT:

Enter the Basic Salary (BS): 15000


The Gross Salary is: 31500.00
Exp 2_2

# Get user input for two numbers


num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))

# Perform arithmetic operations


addition =num1 + num2
subtraction = num1 - num2
multiplication = num1 * num2
division = num1 / num2
modulus = num1 % num2

# Display the results


print(f"Addition: {num1} + {num2} = {addition}")
print(f"Subtraction: {num1} - {num2} = {subtraction}")
print(f"Multiplication: {num1} * {num2} = {multiplication}")
print(f"Division: {num1} / {num2} = {division}")
print(f"Modulus: {num1} % {num2} = {modulus}")

OUTPUT:

Enter the first number: 10


Enter the second number: 5
Addition: 10.0 + 5.0 = 15.0
Subtraction: 10.0 - 5.0 = 5.0
Multiplication: 10.0 * 5.0 = 50.0
Division: 10.0 / 5.0 = 2.0
Modulus: 10.0 % 5.0 = 0.0
Exp_3

# LIST EXAMPLE
# A list can be modified (mutable)
tasks_list = ["Clean the house", "Buy groceries", "Walk the dog"]

# Add tasks to the list


tasks_list.append("Pay bills")
print("After adding a task:", tasks_list)

# Remove a task from the list


tasks_list.remove("Buy groceries")
print("After removing a task:", tasks_list)

# Update a task in the list


tasks_list[1] = "Take the dog to the vet"
print("After updating a task:", tasks_list)

# Sort the tasks alphabetically


tasks_list.sort()
print("After sorting tasks:", tasks_list)

# TUPLE EXAMPLE
# A tuple cannot be modified (immutable), so we cannot directly
add/remove/update tasks
tasks_tuple = ("Clean the house", "Buy groceries", "Walk the dog")

# Adding a task by creating a new tuple


tasks_tuple = tasks_tuple + ("Pay bills",)
print("\nAfter adding a task to tuple:", tasks_tuple)

# Removing a task by converting to a list, modifying, and converting back to a


tuple
temp_list = list(tasks_tuple)
temp_list.remove("Buy groceries")
tasks_tuple = tuple(temp_list)
print("After removing a task from tuple:", tasks_tuple)
# Updating a task (convert to list, modify, and convert back to tuple)
temp_list = list(tasks_tuple)
temp_list[1] = "Take the dog to the vet"
tasks_tuple = tuple(temp_list)
print("After updating a task in tuple:", tasks_tuple)

# Sorting a tuple (convert to list, sort, and convert back to tuple)


temp_list = list(tasks_tuple)
temp_list.sort()
tasks_tuple = tuple(temp_list)
print("After sorting tasks in tuple:", tasks_tuple)

OUTPUT:

After adding a task: ['Clean the house', 'Buy groceries', 'Walk the dog', 'Pay
bills']
After removing a task: ['Clean the house', 'Walk the dog', 'Pay bills']
After updating a task: ['Clean the house', 'Take the dog to the vet', 'Pay bills']
After sorting tasks: ['Clean the house', 'Pay bills', 'Take the dog to the vet']

After adding a task to tuple: ('Clean the house', 'Buy groceries', 'Walk the dog',
'Pay bills')
After removing a task from tuple: ('Clean the house', 'Walk the dog', 'Pay bills')
After updating a task in tuple: ('Clean the house', 'Take the dog to the vet', 'Pay
bills')
After sorting tasks in tuple: ('Clean the house', 'Pay bills', 'Take the dog to the
vet')
Exp_4_1

# Python program to demonstrate the use of sets and perform set operations
# Managing student enrollments in multiple exams

# Sample student enrollments


cet_students = {"Alice", "Bob", "Charlie", "David"}
jee_students = {"Charlie", "Eve", "Frank", "Alice"}
neet_students = {"George", "Hannah", "Alice", "Eve"}

# Display the enrollments


print("Students enrolled in CET:", cet_students)
print("Students enrolled in JEE:", jee_students)
print("Students enrolled in NEET:", neet_students)

# Union: Students appearing for at least one exam


all_students = cet_students.union(jee_students, neet_students)
print("\nStudents appearing for at least one exam:", all_students)

# Intersection: Students appearing for all three exams


common_students = cet_students.intersection(jee_students, neet_students)
print("\nStudents appearing for all three exams:", common_students)

# Difference: Students appearing for CET but not JEE


cet_not_jee = cet_students.difference(jee_students)
print("\nStudents appearing for CET but not JEE:", cet_not_jee)

# Symmetric Difference: Students appearing in CET or JEE but not both


cet_or_jee_not_both = cet_students.symmetric_difference(jee_students)
print("\nStudents appearing in CET or JEE but not both:",
cet_or_jee_not_both)

# Check if a specific student is enrolled in any exam


student_name = "Alice"
is_enrolled = student_name in all_students
print(f"\nIs {student_name} enrolled in any exam?", is_enrolled)

# Add a new student to a specific exam enrollment


cet_students.add("Ivy")
print("\nUpdated CET enrollment after adding Ivy:", cet_students)
# Remove a student from an exam enrollment
jee_students.discard("Frank")
print("\nUpdated JEE enrollment after removing Frank:", jee_students)

OUTPUT:

Students enrolled in CET: {'Charlie', 'Alice', 'David', 'Bob'}


Students enrolled in JEE: {'Charlie', 'Eve', 'Frank', 'Alice'}
Students enrolled in NEET: {'Eve', 'Hannah', 'Alice', 'George'}

Students appearing for at least one exam: {'Alice', 'David', 'Hannah', 'George',
'Frank', 'Eve', 'Bob', 'Charlie'}

Students appearing for all three exams: {'Alice'}

Students appearing for CET but not JEE: {'David', 'Bob'}

Students appearing in CET or JEE but not both: {'Eve', 'David', 'Bob', 'Frank'}

Is Alice enrolled in any exam? True

Updated CET enrollment after adding Ivy: {'Alice', 'David', 'Ivy', 'Bob', 'Charlie'}

Updated JEE enrollment after removing Frank: {'Charlie', 'Eve', 'Alice'}


Exp_4_2

records = {}

# Adding students
records[1] = {"name": "Alice", "grades": [], "attendance": 0}
records[2] = {"name": "Bob", "grades": [], "attendance": 0}

# Updating grades
records[1]["grades"].append(85)
records[1]["grades"].append(90)
records[2]["grades"].append(78)

# Updating attendance
records[1]["attendance"] += 5
records[2]["attendance"] += 3

# Calculating average grade


average_grade_1 = sum(records[1]["grades"]) / len(records[1]["grades"]) if
records[1]["grades"] else None
average_grade_2 = sum(records[2]["grades"]) / len(records[2]["grades"]) if
records[2]["grades"] else None

# Displaying student records


print(f"Student: {records[1]['name']}, Grades: {records[1]['grades']},
Attendance: {records[1]['attendance']} days, Average Grade:
{average_grade_1}")

print(f"Student: {records[2]['name']}, Grades: {records[2]['grades']},


Attendance: {records[2]['attendance']} days, Average Grade:
{average_grade_2}")

Output:

Student: Alice, Grades: [85, 90], Attendance: 5 days, Average Grade: 87.5
Student: Bob, Grades: [78], Attendance: 3 days, Average Grade: 78.0
Exp_5

while True:
num = input("Enter a number (or type -1 to exit): ")
if num == "-1":
print("Exiting program.")
break
if num.isdigit():
num = int(num)
if num % 2 == 0:
print(f"{num} is even.")
else:
print(f"{num} is odd.")
else:
print("Invalid input. Please enter a numerical value.")

Output:
Enter a number (or type -1 to exit): 5
5 is odd.
Enter a number (or type -1 to exit): 8
8 is even.
Enter a number (or type -1 to exit): 7
7 is odd.
Enter a number (or type -1 to exit): 6
6 is even.
Enter a number (or type -1 to exit): 3
3 is odd.
Enter a number (or type -1 to exit): -1
Exiting program.
Exp_6

def fact(n):
if n==0 or n==1:
return 1
else:
return n*fact(n-1)

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


print(f"factorial of {num} is {fact(num)}")

Output:

Enter number: 7
factorial of 7 is 5040
Exp_7_1

def is_prime(number):
if number <=1:
return False
for i in range(2,int(number**0.5)+1):
if number %i ==0:
return False
return True

number= int(input("Enter any integer: "))


print(is_prime(number) and f"{number} is prime" or f"{number} is not prime")

Output:

Enter any integer: 5


5 is prime

Enter any integer: 6


6 is not prime
Exp_7_2

def add(a, b):


return a+b

def diff(a, b):


return a-b

def prod(a, b):


return a*b

def divide(a, b):


if b!=0:
return a/b
else:
return "Division cannot be done by 0."

def calc():
print("Welcome to the calculator: ")
print("\nSelect the operation.")
print("\n1. Addition \n2.Subtraction \n3.Multiplication \n4.Division\n")
c=input("Enter your choice: ")

if c in ('1', '2', '3', '4'):


n1 = float(input("Enter the first number: "))
n2 = float(input("Enter the second number: "))
if c=='1':
print(f"The result is: {add(n1,n2)}")
if c=='2':
print(f"The result is: {diff(n1,n2)}")
if c=='3':
print(f"The result is: {prod(n1,n2)}")
if c=='4':
print(f"The result is: {division(n1,n2)}")
else:
print("Invalid input. Please select a valid operation.")

calc()
Output:

Welcome to the calculator:

Select the operation.

1. Addition
2.Subtraction
3.Multiplication
4.Division

Enter your choice: 3


Enter the first number: 5
Enter the second number: 4
The result is: 20.0
Exp_8

import re

filename = input("Enter the filename: ")


obj=open(filename,"w")
obj.write("hi these file contains three four and five length string words !!!")
obj.close()

n = int(input("Enter the number elements in lengths: "))


lengths = []
for i in range(n):
num = int(input(f"Enter length {i+1}: "))
lengths.append(num)

with open(filename, 'r') as file:


words = re.findall(r'\b[a-zA-Z]+\b', file.read())

for length in lengths:


filtered_words = [word for word in words if len(word) == length]
print(f'Words of length {length}:', filtered_words)

Output:

Enter the filename: abcd.txt


Enter the number elements in lengths: 5
Enter length 1: 4
Enter length 2: 3
Enter length 3: 2
Enter length 4: 5
Enter length 5: 1
Words of length 4: ['file', 'four', 'five']
Words of length 3: ['and']
Words of length 2: ['hi']
Words of length 5: ['these', 'three', 'words']
Words of length 1: []

Exp_9
try:
num1 = int(input("Enter a numerator for division: "))
num2 = int(input("Enter a denomenator for division: "))
result = num1 / num2
print("Result:", result)

except ValueError:
print("Error: Invalid input! Please enter a number.")

except ZeroDivisionError:
print("Error: Cannot divide by zero!")

except Exception as e:
print("An unexpected error occurred:", e)

finally:
print("Execution completed.")

Output:

Enter a numerator for division: 5


Enter a denomenator for division: 0
Error: Cannot divide by zero!
Execution completed.

Exp_10
import pdb

def divide(a, b):


return a / b # Might cause ZeroDivisionError

x, y = 10, 5# Intentional error

pdb.set_trace() # Start debugging


result = divide(x, y)
print(result)

output:

> c:\users\admin\desktop\python programs\pydeb2.py(8)<module>()


-> pdb.set_trace() # Start debugging
(Pdb) n
> c:\users\admin\desktop\python programs\pydeb2.py(9)<module>()
-> result = divide(x, y)
(Pdb) s
--Call--
> c:\users\admin\desktop\python programs\pydeb2.py(3)divide()
-> def divide(a, b):
(Pdb) p x
10
(Pdb) p y
5
(Pdb) p a
10
(Pdb) p b
5
(Pdb) n
> c:\users\admin\desktop\python programs\pydeb2.py(4)divide()
-> return a / b # Might cause ZeroDivisionError
(Pdb) n
--Return--
> c:\users\admin\desktop\python programs\pydeb2.py(4)divide()->2.0
-> return a / b # Might cause ZeroDivisionError
(Pdb) n
> c:\users\admin\desktop\python programs\pydeb2.py(10)<module>()
-> print(result)
(Pdb) n
2.0
--Return--
> c:\users\admin\desktop\python programs\pydeb2.py(10)<module>()->None
-> print(result)
(Pdb) q

You might also like