0% found this document useful (0 votes)
4 views106 pages

All Python Assignment of semester 1 for ssn students

The document contains a detailed assignment with multiple parts, including tasks related to Linux commands, Python programming, and pseudocode development. It covers various topics such as file management, directory creation, and calculations for interest and property tax, along with flowcharts and pseudocode for problem-solving. Additionally, it includes additional problems that reinforce programming concepts and logical thinking.

Uploaded by

srisubhiksha2006
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)
4 views106 pages

All Python Assignment of semester 1 for ssn students

The document contains a detailed assignment with multiple parts, including tasks related to Linux commands, Python programming, and pseudocode development. It covers various topics such as file management, directory creation, and calculations for interest and property tax, along with flowcharts and pseudocode for problem-solving. Additionally, it includes additional problems that reinforce programming concepts and logical thinking.

Uploaded by

srisubhiksha2006
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/ 106

ASSIGNMENT 1

PART C) Assignment

1) Display the name of your home directory.


Ans: ~$ pwd
/home/s3
2) Print the name of the operating system.
Ans: ~$uname
Linux
3) Print the login name. Ans: $ whoami
s3

4) Create a new directory named “SSN”, a subdirectory “BE” under SSN and create a
file named “lifeatssn.txt” and write about the SSN life that you experienced so far. Ans:
~$ mkdir SSN
~$ cd SSN
~/SSN$ mkdir BE
~/SSN$ cd BE
~SSN/BE$ cat>lifeatssn
Hi, this is Sri Subhiksha. My life here is very cool. I am happy that I have joined
here.
I can feel the sense of liberty here! I love SSN.

5) Display the content of the file lifeatssn.txt.


Ans: ~/SSN/BE$ cat lifeatssn
Hi, this is Sri Subhiksha. My life here is very cool. I am happy that I have joined here.
I can feel the sense of liberty here! I love SSN.

6) Append more lines in the lifeatssn.txt.


1
Ans: ~/SSN/BE$ cat>>lifeatssn "SSN is the path for
Success." This is what I believe.

7) Rename the lifeatssn.txt file as firstexp.txt. Ans: ~/SSN/BE$ mv lifeatssn firstexp

8) Give all permissions to user and only read permission to others. Ans: ~/SSN/BE$
chmod u=rwx,o=r firstexp

9) Create a file “AboutMe.txt” and write about yourself and your ambitions.
Ans: ~/SSN/BE$ cat>AboutMe
I am Sri Subhiksha. I wish to succeed in my life in either of the two ways... One is to have
fame and money and the other way is just having money. I know that this does not sound
so good. But this is what I need in my life. I wish to do charity right after I become rich.
That’s it!!

10) Create two directories namely “dept_x” (x being your dept name), “SEC_X”
inside “SSN” folder. Ans: ~/SSN/BE$ cd ..
~/SSN$ mkdir dept_x ~/SSN$
mkdir SEC_X

11) Create a file named “dept.txt” and write about your department in that file.
Ans: ~/SSN$ cd dept_x
~/SSN/dept_x$ cat>dept
My department is Information Technology. I have heard it from the seniors that it is the
coolest department in this entire campus. I don’t get it. Maybe I will experience it in the
upcoming days.

12) Copy the file named “firstexp.txt” to “SEC_X” folder.


Ans: ~/SSN$ cd BE
~/SSN$ cp firstexp SEC_X

13) Move the file “dept.txt” to “SEC_X" folder. Ans: ~/SSN/BE$ cd ..


~/SSN$ cd dept_x
~/SSN/dept_x$ mv dept SEC_X

14) Enter folder “SEC_X” and list the folder content.


2
Ans: ~/SSN$ cd SEC_X
~/SSN/SEC_X$ ls ~/SSN/SEC_X$
dept

15) Move to “SSN” folder and list all the contents.


Ans: ~/SSN/SEC_X$ cd ..
~/SSN$ ls
~/SSN$ BE dept_x SEC_X

16) Delete the file dept.txt Ans: ~/SSN$ rm dept

17) Remove the folder “SEC_X” Ans: ~/SSN$ rmdir SEC_X

18) Display the calendar for a. Jan 2000


b. Feb 1999
c. 9 th month of the year 1977
d. For the current month

19) Display the Current Date and Current Time.


20) Display the time in 12-Hour and 24-Hour Notations.
21) Current Date Day Abbreviation, Month Abbreviation along with year
22) Print “Hello Welcome to Linux shell Programming”.

Ans:

3
4
5
Name: T. Sri Subhiksha Class: S3

Assignment 2
Solve the following problems using Python (CO1, K3, 1.3.1)

Aim: To enhance the understanding about the required inputs and the types of
statements to be employed in the pseudocode and the program to get the desired output.

1. Assume a man “X” purchased items of worth ₹5000 using his credit card. The annual
percentage rate (APR) is 15% and his average daily balance (ADB) is 1000 INR. Compute the
daily periodic rate (DPR). Compute the interest he has to pay for a month and also compute
the per day interest the customer has to pay, if he has not repaid the amount within the due
date.

a. Identify the inputs required to solve the problem.


1. Ans: Annual Percentage Rate (APR): 15%
2. Average Daily Balance (ADB): ₹1000
3. Number of days in a year: 365 (standard for daily periodic rate calculation)
4. Number of days in a month: 30 (assuming a 30-day month for simplicity)

b. Identify the type of statements required.


1. Ans: Input Statements: To get the APR and ADB.
2. Calculation Statements: To compute the Daily Periodic Rate (DPR), monthly interest,
and daily interest.
3. Output Statements: To display the computed DPR, monthly interest, and daily
interest.

6
c. Devise a solution and represent the same using flowchart and pseudocode. Flowchart:

Start

Input APR, ADB

Calculate DPR:
DPR=APR/365

Calculate monthly interest:


Monthly_Interest = ADB *
DPR * 30

Calculate Daily
interest:
Daily_Interest = ADB
* DPR

Output DPR,
Monthly Interest,
Daily Interest

End

Pseudocode:
START
INPUT APR, ADB
DPR = APR / 365
Monthly_Interest = ADB * DPR * 30
Daily_Interest = ADB * DPR
OUTPUT DPR, Monthly_Interest, Daily_Interest

7
END

d. Develop a program to compute the daily periodic rate, per day interest and the interest
the customer has to pay for a month for the outstanding amount.
Program:
APR = 15
ADB = 1000
DPR = APR / 365 / 100
Monthly_Interest = ADB * DPR * 30
Daily_Interest = ADB * DPR
print(f"Daily Periodic Rate (DPR): {DPR:.6f}")
print(f"Monthly Interest: ₹{Monthly_Interest:.2f}")
print(f"Daily Interest: ₹{Daily_Interest:.2f}")

Output:
Daily Periodic Rate (DPR): 0.000411
Monthly Interest: ₹12.33
Daily Interest: ₹0.41

8
c. Devise a solution and represent the same using flowchart and pseudocode.
Flowchart:
Start

Input Guidance Value per Square


Meter, Build-up Area, Municipal
Tax Rate

Calculate DPR: Annual_Value =


Guidance_Value_per_Square_Meter * Build_up_Area

Calculate Property_Tax
Property_Tax= Annual_Value
* Municipal_Tax_Rate

OUTPUT
Annual_Value,
Property_Tax

End

Pseudocode:
START
INPUT Guidance_Value_per_Square_Meter, Build_up_Area, Municipal_tax_Rate
Annual_Value = Guidance_Value_per_Square_Meter * Build_up_Area
Property_Tax = Annual_Value * Municipal_Tax_Rate
OUTPUT Annual_Value, Property_Tax
END

d. Develop a program to compute the annual value of the property and its property tax, for
a given guidance value.
Program:
9
guidance_value_per_square_meter = float(input("Enter the guidance value per square
meter (in INR): "))
build_up_area = float(input("Enter the build-up area (in square meters): "))
municipal_tax_rate = float(input("Enter the municipal tax rate (as a decimal, e.g., 0.1 for
10%): "))
annual_value = guidance_value_per_square_meter * build_up_area
Property_tax = annual_value * municipal_tax_rate
print(f"Annual Value: ₹{annual_value:.2f}")
print(f"Property Tax: ₹{Property_tax:.2f}")

Output:
Enter the guidance value per square meter (in INR): 1500
Enter the build-up area (in square meters): 5000
Enter the municipal tax rate (as a decimal, e.g., 0.1 for 10%): 0.25
Annual Value: ₹7500000.00
Property Tax: ₹1875000.00

Additional Problems :
1. Write a program to convert miles to kilometers. (Hint: 0.621 mile = 1 kilometer)
Ans: miles=float(input(“Enter the no. of miles : “))
print(miles,” is “,miles/0.621,” kms”)
Output:
Enter the no. of miles : 0.621
0.621 is 1.0 kms

2. Write a program to find the square root of a number (don’t use built-in function)
Ans: num=float(input(“Enter a non-negative number : “))
while num<0:
num=float(input(“Please enter a positive number : “))
10
print(“The square root of “,num,” is “,num**(1/2))
Output:
Enter a non-negative number : -9
Please enter a positive number : -8
Please enter a positive number : 4
The square root of 4.0 is 2.0

3. A person invests ₹20,000 into a savings account for 10 years at an annual interest rate of
5%, compounded monthly. Find out his investment balance after 15 years. (Hint: A = P(1 +
r/n)^nt).
Ans: P = 20000
r = 0.05
n = 12
t = 15
A = P * (1 + r / n) ** (n * t)
print(f"The investment balance after {t} years is: ₹{A:.2f}")
Output:
The investment balance after 15 years is: ₹42274.08

4. Write a program to find the area of a triangle using Heron’s formula given 3 sides as
follows: a=3, b=6, c=8 respectively.
Ans: a,b,c=3,6,8
s=(a+b+c)/2
area=(s*(s-a)*(s-b)*(s-c))**(1/2)
print(“The area of the given triangle is, “,area)
Output:
The area of the given triangle is, 7.644442425710328

5. Write a program to convert lowercase character to uppercase character and print.

11
Ans: word=input(“Please enter a string : “)
print(word.upper())
Output:
Please enter a string : hihello
HIHELLO

12
Assignment 3
Solve the following problems using Python (CO2, K3, 1.3.1, 1.4.1, 13.3.1)

1) Ans:
Aim: To write a python program for “XMart”, which calculates the final amount to be paid
after applying a discount based on the total purchase amount.
a. Inputs required : The total amount spent for purchase.
b. Devise a solution and represent the same using flowchart and pseudocode.
Flowchart:

Start

Input Purchase

False
If
purchase>5000
00
True
False
Discount=15% ,calculate If
Discounted=purchase- purchase>2000
(Discount*Purchase)
True
Discount=15% ,calculate
Discounted=purchase- If
(Discount*Purchase) purchase>1000
00
True

End Discount=15% ,calculate Discount=0%


Discounted=purchase- Discounted=Purchase
(Discount*Purchase)

13
Pseudocode:
START
INPUT Purchase
IF Purchase>5000:
Discounted=Purchase-(Purchase*(15/100))
IF Purchase>2000:
Discounted=Purchase-(Purchase*(10/100))
IF Purchase>1000:
Discounted=Purchase-(Purchase*(5/100))
OUTPUT Discounted
END

c. purchase=float(input("Enter the amount of purchase : "))


discounted=0
if purchase>5000:
discounted=purchase-((15/100)*purchase)
elif purchase>2000:
discounted=purchase-((10/100)*purchase)
elif purchase>1000:
discounted=purchase-((5/100)*purchase)
else:
discounted=purchase
print("Welcome to XMart! Your actual amount before discount is: Rs[",purchase,"]")
print(" Your final amount after discount is: Rs[",discounted,"]")

Output:
Enter the amount of purchase : 9000
Welcome to XMart! Your actual amount before discount is: Rs[ 9000.0 ]
Your final amount after discount is: Rs[ 7650.0 ]

14
Result: A python program for “XMart”, which calculates the final amount to be paid after
applying a discount based on the total purchase amount is written.
Learning objectives: Learnt to use conditional statements along with the development of the
sense of logical thinking by analyzing various test cases.

2) Ans:
Aim: To write a python program to compute the total wage for the employee based on
the inputs inclusive of printing the output message accordingly if the age does not fall
within the specified range.
a. Inputs required: Age, Gender
b. Devise a solution and represent the same using flowchart and pseudocode.
Flowchart:

Start

Input Age, Gender

False False
elif age>=31
If age>=19 and age<=40
and age<=30

True False True False


If If
Print(“Enter
gender gender
==”M”
Appropriate
==”M”
age”)

Wage = 800 Wage = 850 Wage = 900 Wage = 950

End

15
Pseudocode:
START
Input Age, Gender
IF Age>=19 and Age<=30:
IF Gender==”M”:
Wage=800
Else:
Wage=850
ELIF Age>=31 and Age<=40:
IF Gender==”M”:
Wage=900
Else:
Wage=950
ELSE:
Output (“Enter Appropriate age”)
END

c. Program
Age=int(input("Enter your age: "))
Gender=input("Enter Your Gender: ")
if Age>=19 and Age<=30:
if Gender=="M":
Wage=800
else:
Wage=850
print("The wage = ",Wage)
elif Age>=31 and Age<=40:
if Gender=="M":
16
Wage=900
else:
Wage=950
print("The wage = ",Wage)
else:
print ("Enter Appropriate age")

Output:
Enter your age: 40
Enter Your Gender: M
The wage = 900

Result: A python program to compute the total wage for the employee based on the inputs
inclusive of printing the output message accordingly if the age does not fall within the
specified range is written.
Learning objectives: Learnt to use conditional statements along with the development of
the sense of logical thinking by analyzing various test cases.

Additional Problems:
1) num=int(input(“Enter a number between 1 and 100: “))
if num>=1 and num<=100:
print(“The number is between 1 and 100”)
else:
print(“The number is not between 1 and 100”)
2) a=float(input("Enter the length of the first side of the triangle: "))
b=float(input("Enter the length of the second side of the triangle: "))
c=float(input("Enter the length of the third side of the triangle: "))
if (a==b==c):
print("The given triangle is an equilateral triangle.")
17
elif (a==b or a==c or b==c):
print("The given triangle is an isosceles triangle.")
else:
print("The given triangle is a scalene triangle.")
3) a=float(input("Enter the first number :"))
b=float(input("Enter the second number : "))
c=float(input("Enter the third number : "))
if(a<b and a<c):
print(a," is the smallest number.")
elif (b<a and b<c):
print(b," is the smallest number.")
elif (c<a and c<b):
print(c," is the smallest number.")
else:
print("All the numbers are equal.")

4) num=int(input("Enter a single digit number: "))


while num>=10:
num=int(input("Please enter a single digit number :"))
if num==1:
print("One")
elif num==2:
print("Two")
elif num==3:
print("Three")
elif num==4:
print("Four")
elif num==5:
18
print("Five")
elif num==6:
print("Six")
elif num==7:
print("Seven")
elif num==8:
print("Eight")
else:
print("Nine")
5) days=int(input("Enter the number of days you are late to return the book: "))
if days<=5:
print("The fine is 50 paise.")
elif days>=6 and days<=10:
print("The fine is 1 rupee.")
elif days>=10 and days<=30:
print("The fine is 5 rupees.")
else:
if days>30:
print("Your membership is cancelled.")
6) sub1=float(input("Enter the marks for Subject 1: "))
sub2=float(input("Enter the marks for Subject 2: "))
sub3=float(input("Enter the marks for Subject 3: "))
sub4=float(input("Enter the marks for Subject 4: "))
sub5=float(input("Enter the marks for Subject 5: "))
per=(sub1+sub2+sub3+sub4+sub5)/5
if per>=90:
print("Distinction")
elif per >=80 and per <90:
19
print("First Class")
elif per >=70 and per <80:
print("Second Class")
elif per >=60 and per <70:
print("Third Class")
else:
if per<60:
print("Fail")

20
Assignment-4

Name: T. Sri Subhiksha Class: S-03

1)
Aim:
To write a program to simulate a vending machine which has the ability to cancel the
transaction at any point of time along with providing the choice of purchase to the user.

Program:
flag=1
while flag==1:
print("The products available in this vending machine are:\n1)Candy\n2)Cake\n3)Juice")
prod=int(input("Enter the number corresponding to your desired product: "))
while(prod!=1 and prod!=2 and prod!=3):
print("Enter a valid input!")
prod=int(input("Enter the number corresponding to your desired product: "))
if prod==1:
item="Candy"
cost=25
print(item," ",cost," rs")
elif prod==2:
item="Cake"
cost=100
print(item," ",cost," rs")
else:
if prod==3:
item="Juice"

21
cost=45
print(item," ",cost," rs")
print("You can type 'Cancel' at any point of transaction to cancel the transaction")
amount=0
pay=input("Enter the above amount : ")
if pay.lower()=="cancel":
print("The transaction cancelled.")
continue
while (pay.isalpha()==True):
print("Enter valid input!")
pay=input("Enter the above amount : ")
amount=float(pay)
while (amount<cost):
print("The remaining amount:",(cost-amount))
repay=input("Enter the above amount : ")
if repay.lower()=="cancel":
print("The transaction cancelled.")
break
amount=amount+float(repay)
if amount>cost:
print("The amount to be rendered as change: ",abs(cost-amount))
amount=cost
if amount==cost:
print("The transaction is completed and your order is placed.")
print("Item: ",item,"\t\tCost: ",cost)
choice=input("Do you want to shop? (Yes/No)\n")
if choice.lower()=="yes":
flag=1
22
elif choice.lower()=="no":
flag=0
else:
print("Enter valid input!")
continue

Output:
The products available in this vending machine are:
1)Candy
2)Cake
3)Juice
Enter the number corresponding to your desired product: 1
Candy 25 rs
You can type 'Cancel' at any point of transaction to cancel the transaction
Enter the above amount : 20
The remaining amount: 5.0
Enter the above amount : 10
The amount to be rendered as change: 5.0
The transaction is completed and your order is placed.
Item: Candy Cost: 25
Do you want to shop? (Yes/No)
Yes
The products available in this vending machine are:
1)Candy
2)Cake
3)Juice
Enter the number corresponding to your desired product: 2
Cake 100 rs
23
You can type 'Cancel' at any point of transaction to cancel the transaction
Enter the above amount : 100
The transaction is completed and your order is placed.
Item: Cake Cost: 100
Do you want to shop? (Yes/No)
no

Result:
A program to simulate a vending machine which has the ability to cancel the transaction at
any point of time along with providing the choice of purchase to the user is written.

Learning objectives:
The usage of iterative statements with the understanding of the control flow of such
statements is the remarkable objective.

2) Soln:
Aim:
To write a program to print a number diamond in accordance to the number given by the
user as input.

Program:
num=int(input("Enter a number for magic: "))
n=num
for i in range(1,(num+1)):
print(" "*(n-1),str(i)*((i*2)-1))
n=n-1
for i in range((num-1),0,-1):
print(" "*(n+1),str(i)*((i*2)-1))
n=n+1
24
Output:

Enter a number for magic: 5


1
222
33333
4444444
555555555
4444444
33333
222
1

Result:
A program to print a number diamond in accordance to the number given by the user as
input is written.

Learning objective: The usage of FOR loop is emphasized here. The control flow of FOR loop
is well explained by this program.

Assignment-5
Functions

25
1. Simple Banking system:

Aim:
To write a python program to simulate a simple banking system using the ideology of
functions.

Program:
#Deposit
def Deposit(balance):
amount=float(input("Enter the amount to be deposited (in terms of numbers) : "))
b=balance+amount
d=str(amount)+" is successfully deposited."
print(d)
history.append(d)
return (b)
#withdraw
def withdraw(balance):
amount=float(input("Enter the amount to be withdrawn: "))
while amount<=balance:
b=balance-amount
w=str(amount)+" is successfully withdrawn."
print(w)
history.append(w)
return(b)
else:
print("Insufficient balance!")
amount=float(input("Enter the amount to be withdrawn: "))

26
#check balance
def checkbalance(balance):
print("Your balance is : ",balance)
#exit
def Exit():
print("See you again on your next transaction! Good Bye! :)")
flag=2
return(flag)
#Transaction history
def transaction_history(history):
print("\n")
for i in history:
print(i)
#Main Program:
print("The menu of operations :\n1) Deposit\n2) Withdraw\n3) Check Balance\n4)
Transaction History\n5) Exit")
flag=1
history=[]
balance=0
while(flag==1):
choice=int(input("Enter your choice of operation: "))
if choice==1:
balance=Deposit(balance)
elif choice==2:
balance=withdraw(balance)
elif choice==3:
checkbalance(balance)
elif choice==4:

27
transaction_history(history)
elif choice==5:
flag=Exit()
else:
flag=1

Pseudocode:
Start
Display menu of operations:
1) Deposit
2) Withdraw
3) Check Balance
4) Transaction History
5) Exit

Set flag to 1
Initialize history as an empty list
Initialize balance to 0

While flag is 1:
Prompt user to enter choice of operation
If choice is 1:
Call Deposit function with balance
Update balance with returned value
Else if choice is 2:
Call Withdraw function with balance
Update balance with returned value
Else if choice is 3:
28
Call CheckBalance function with balance
Else if choice is 4:
Call TransactionHistory function with history
Else if choice is 5:
Call Exit function
Update flag with returned value
Else:
Set flag to 1

Deposit Function:
Prompt user to enter the deposit amount
Add deposit amount to balance
Append deposit transaction to history
Return new balance

Withdraw Function:
Prompt user to enter the withdrawal amount
While withdrawal amount is less than or equal to balance:
Subtract withdrawal amount from balance
Append withdrawal transaction to history
Return new balance
If withdrawal amount is more than balance:
Print "Insufficient balance!"
Prompt user to enter withdrawal amount again

CheckBalance Function:
Display current balance

29
Exit Function:
Print "See you again on your next transaction! Good Bye! :)"
Set flag to 2
Return flag

TransactionHistory Function:
Print each transaction in history

End

Output:
The menu of operations :
1) Deposit
2) Withdraw
3) Check Balance
4) Transaction History
5) Exit
Enter your choice of operation: 1
Enter the amount to be deposited (in terms of numbers) : 5000
5000.0 is successfully deposited.
Enter your choice of operation: 2
Enter the amount to be withdrawn: 2000
2000.0 is successfully withdrawn.
Enter your choice of operation: 3
Your balance is : 3000.0
Enter your choice of operation: 4

30
5000.0 is successfully deposited.
2000.0 is successfully withdrawn.
Enter your choice of operation: 5
See you again on your next transaction! Good Bye! :)

Learning Outcomes:
 I understood the importance of logical thinking and applying the technical knowledge
into real life applications.
 I gained the knowledge about the modularisation of programs.
 I learnt how to use the concept of functions.
 I finally understood how big complex tasks seamlessly work in their background.

2. Employee Payroll Generator

Aim:
To write a python program to generate payroll for employees in accordance to certain
parameters given in the question.

Program:

def calculate_weekly_salary(hourly_wage, hours_worked):


if hours_worked > 40:
overtime_hours = hours_worked - 40
weekly_salary = (hourly_wage * 40) + (overtime_hours * hourly_wage * 1.5)
else:
weekly_salary = hourly_wage * hours_worked
return weekly_salary

31
def calculate_bonus(performance_score, annual_salary):
if performance_score >= 90:
bonus = 0.10 * annual_salary
elif performance_score >= 80:
bonus = 0.05 * annual_salary
else:
bonus = 0
return bonus

def calculate_tax(net_salary):
if net_salary <= 3000:
tax = 0
elif net_salary <= 8000:
tax = net_salary * 0.10
elif net_salary <= 15000:
tax = net_salary * 0.20
else:
tax = net_salary * 0.30
return tax

def generate_payroll_report(employee_name, hourly_wage, hours_worked,


performance_score, annual_salary):
weekly_salary = calculate_weekly_salary(hourly_wage, hours_worked)
bonus = calculate_bonus(performance_score, annual_salary)
gross_salary = weekly_salary + bonus
tax = calculate_tax(gross_salary)
net_salary = gross_salary - tax
total_compensation = weekly_salary + bonus

32
report = f"Employee Name: {employee_name}\nWeekly Salary: ${weekly_salary:.2f}\
nBonus: ${bonus:.2f}\nNet Salary (after tax): ${net_salary:.2f}\nTotal Compensation: $
{total_compensation:.2f}"
return report

#Main program:
flag = 1
while flag == 1:
print("Enter employee data to generate a payroll report:")
employee_name = input("Employee Name: ")
hourly_wage = float(input("Hourly Wage: "))
hours_worked = float(input("Hours Worked: "))
performance_score = float(input("Performance Score: "))
annual_salary = float(input("Annual Salary: "))

report = generate_payroll_report(employee_name, hourly_wage, hours_worked,


performance_score, annual_salary)
print(report)

choice = int(input("Do you want to generate another report? (1 for Yes, 0 for No): "))
if choice != 1:
flag = 0

Pseudocode:

Start
Function calculate_weekly_salary(hourly_wage, hours_worked):
If hours_worked > 40:
overtime_hours = hours_worked - 40

33
weekly_salary = (hourly_wage * 40) + (overtime_hours * hourly_wage * 1.5)
Else:
weekly_salary = hourly_wage * hours_worked
Return weekly_salary

Function calculate_bonus(performance_score, annual_salary):


If performance_score >= 90:
bonus = 0.10 * annual_salary
Else if performance_score >= 80:
bonus = 0.05 * annual_salary
Else:
bonus = 0
Return bonus

Function calculate_tax(net_salary):
If net_salary <= 3000:
tax = 0
Else if net_salary <= 8000:
tax = net_salary * 0.10
Else if net_salary <= 15000:
tax = net_salary * 0.20
Else:
tax = net_salary * 0.30
Return tax

Function generate_payroll_report(employee_name, hourly_wage, hours_worked,


performance_score, annual_salary):
weekly_salary = calculate_weekly_salary(hourly_wage, hours_worked)

34
bonus = calculate_bonus(performance_score, annual_salary)
gross_salary = weekly_salary + bonus
tax = calculate_tax(gross_salary)
net_salary = gross_salary - tax
total_compensation = weekly_salary + bonus
report = "Employee Name: " + employee_name + "\nWeekly Salary: $" + weekly_salary +
"\nBonus: $" + bonus + "\nNet Salary (after tax): $" + net_salary + "\nTotal Compensation:
$" + total_compensation
Return report

Function main():
flag = 1
While flag == 1:
choice = Input "Enter your choice of operation: "
If choice == 1:
balance = Deposit(balance)
Else if choice == 2:
balance = withdraw(balance)
Else if choice == 3:
checkbalance(balance)
Else if choice == 4:
transaction_history(history)
Else if choice == 5:
flag = Exit()
Else:
flag = 1

End

35
Outcome:
Enter employee data to generate a payroll report:
Employee Name: Arun
Hourly Wage: 900
Hours Worked: 45
Performance Score: 9.8
Annual Salary: 100000
Employee Name: Arun
Weekly Salary: $42750.00
Bonus: $0.00
Net Salary (after tax): $29925.00
Total Compensation: $42750.00
Do you want to generate another report? (1 for Yes, 0 for No): 1
Enter employee data to generate a payroll report:
Employee Name: Adhi
Hourly Wage: 100
Hours Worked: 65
Performance Score: 10
Annual Salary: 1000000
Employee Name: Adhi
Weekly Salary: $7750.00
Bonus: $0.00
Net Salary (after tax): $6975.00
Total Compensation: $7750.00
Do you want to generate another report? (1 for Yes, 0 for No): 0

Learning Outcomes:

36
 I learnt how to use conditional and iterative statements to achieve the solution of a
problem.
 Helped me to gain knowledge about the actual waging system.
 This program taught me to structure and plan the solution of a problem strategically.

37
Assignment 6
Name: Sri Subhiksha. T
Class: S-03

1) Print numbers from n down to 0.


Aim: To write a recursive program to print numbers from n to 0.
Program:
def recprintnum(num):
print(num,end=" ")
if num>0:
recprintnum(num-1)
else:
pass
n=int(input("Enter a number :"))
recprintnum(n)

Pseudocode:
Function recprintnum(num):
Print num with a space at the end
If num is greater than 0:
Call recprintnum(num - 1)
EndIf
Main:
Prompt user to enter a number and read the input as n
Call recprintnum(n)

Output:
Enter a number :8
38
876543210

Learning outcomes:
 With this program, I learnt the principle of recursion in a very elementary manner.
 In this program, the function “recprintnum” got its name as this is a recursive
function used to print a number.

2) Reverse the digits of a number.


Aim: To write a recursive program to reverse the digits of a number.
Program:
def recreverse(n):
if (n%10!=0):
print(n%10,end="")
recreverse(n//10)
else:
pass
num=int(input("Enter a number : "))
recreverse(num)

Pseudocode:
Function recreverse(n):
If n % 10 is not equal to 0:
Print n % 10 with a space at the end
Call recreverse with n divided by 10 (integer division)
EndIf

Main:
Prompt user to enter a number and read the input as num
Call recreverse(num)

39
Output:
Enter a number : 987
789

Learning outcomes:
 In this function, we learnt how to reverse the digits recursively.
 The function got its name “recreverse” as it is a function which uses to recursion to
reverse the digits.

3) Find the value of combinations.


Aim: To write a recursive program to find the value of combination.
Program:
def combination(n, k):
if k == 0 or k == n:
return 1
else:
return combination(n - 1, k - 1) + combination(n - 1,k)
n=int(input("n ="))
r=int(input("r= "))
ans=combination(n,r)
print(ans)

Pseudocode:
Function combination(n, k):
If k equals 0 or k equals n:
Return 1
40
Else:
Return combination(n - 1, k - 1) + combination(n - 1, k)
Main:
Prompt user to enter the value of n and read the input as n
Prompt user to enter the value of r and read the input as k
Call combination(n, k) and store the result in ans
Print ans

Output:
n =5
r= 2
10

Learning outcomes:
 From this program, I learnt how to use recursion in finding the value of
combinations.
 I also learnt from this program about how important it is to have mathematical
knowledge to arrive on the logic for coding.

4) Check if a given number is a palindrome.


Aim: To write a program to recursively calculate whether a given number is palindrome
or not.
Program:
def recpalindrome(n):
s=str(n)
if len(s)<=1:
print("The number is palindrome.")
else:
if s[0]==s[-1]:
recpalindrome(s[1:-1])
41
else:
print("The number is not Palindrome.")
num=int(input("Enter a number : "))
recpalindrome(num)

Pseudocode:
Function recpalindrome(n):
Convert n to a string s
If the length of s is less than or equal to 1:
Print "The number is palindrome."
Else:
If the first character of s is equal to the last character of s:
Call recpalindrome with s excluding the first and last characters
Else:
Print "The number is not Palindrome."
EndIf
Main:
Prompt user to enter a number and read the input as num
Call recpalindrome(num)

Output-1:
Enter a number : 101
The number is palindrome.
Output-2:
Enter a number : 100
The number is not Palindrome.

Learning Outcomes :
42
 In this program, I learnt how to recursively check whether a given number is
palindrome or not.
 The function got its name as it is a recursive function used to check whether a
given number is palindrome or not.

5) Rabbit Population Growth:

Imagine that we have a pair of rabbits (one male and one female) that are grown in a
farm. These rabbits reproduce in a very specific way:
1. It takes one month for a pair of rabbits to mature and reproduce.
2. After one month, each pair produces another pair (one male and one female).
3. Rabbits never die (that’s strange!) and continue reproducing.
Write a recursive function to compute the number of pairs of rabbits that will be
there after n months.
Hint: In month 1, we start with 1 pair of rabbits. In month 2, the original pair matures,
but there’s still only 1 pair. In month 3, the first pair reproduces, so now there are 2
pairs. In month 4, the first pair produces another new pair, and the second pair
matures, so now there are 3 pairs. In month 5, the first pair and the second pair both
reproduce, so now there are 5 pairs. Each new generation of rabbits comes from the
sum of the number of pairs that already exist and the number of new pairs being
produced.

Aim: To write a recursive program to solve the above said problem.

Program:
def rabbit_pairs(n): # Base cases
if n == 1:
return 1
elif n == 2:
return 1 # Recursive case
else:

43
return rabbit_pairs(n - 1) + rabbit_pairs(n - 2)
n=int(input("Enter the number of months : "))
r=rabbit_pairs(n)
print("The no.of pairs of rabbits : ",r)

Pseudocode:
Function rabbit_pairs(n):
If n is equal to 1:
Return 1
Else if n is equal to 2:
Return 1
Else:
Return rabbit_pairs(n - 1) + rabbit_pairs(n - 2)
Main:
Prompt user to enter the number of months and read the input as n
Call rabbit_pairs(n)

Output:
Enter the number of months : 10
The no.of pairs of rabbits : 55

Learning Outcomes:
 This program is nothing but a variant of the problem statement whose purpose
is to code the solution to find a Fibonacci series.
 So, this program made me understand that the problems can sound complex
but with unwavering mind and proper analysis, the solutions can be easily
coded.

44
45
GE3188 PROBLEM SOLVING AND PYTHON PROGRAMMING
Assignment 6: Programs using strings without built-in functions

Solve the following problems using Python (CO3, K3, 1.3.1, 1.4.1, 13.3.1)

1. Read the names of audio files and check whether the following naming conventions are
followed or not:
Naming convention to be verified:
1. The first three characters in the filename specify the speaker id.
2. The file name should begin with ‘s’. ‘s’ refers to the speaker.
3. Next two digits are in the range 02-55, to uniquely identify a speaker.
4. The first three characters are followed by either of these 2 patterns, _p_ or _l_ and
followed by a string of length 6.
5. If the filename has the pattern _p_, then display them.
6. If the filename has the pattern _l_, then display them.
7. The filename has the extension .wav
8. If the filename doesn’t follow the above said rules, print them as invalid.

Aim:
To write a python program to check wtheter the given name of an audio file is following the
above said rules.

Program:

print("The conventions of file name:")


print("1. The first three characters in the filename should specify specify the speaker id.")
print("2. The file name should begin with ‘s’. ‘s’ refers to the speaker.")

46
print("3. Next two digits are in the range 02-55, to uniquely identify a speaker.")
print("4. The first three characters must be followed by either of these 2 patterns, _p_ or _l_
and followed by a string of length 6.")
print("5. If the filename has the pattern _p_, then display them.")
print("6. If the filename has the pattern _l_, then display them.")
print("7. The filename has the extension .wav")
print("8. If the filename doesn’t follow the above said rules, print them as invalid.")
flag=1
while (flag==1):
s=input("Enter the filename: ")
print(s[0],s[1:3],s[3:6],s[6:12],s[12])
if s[0]!="s":
print("The file name should begin with ‘s’. ‘s’ refers to the speaker.")
elif int(s[1:3])<2 or int(s[1:3])>55:
print("The digits in the speaker id are supposed to be within the range 02-55, to
uniquely identify a speaker.")
elif str(s[3:6])!="_l_" and str(s[3:6])!="_p_":
print(" The filename must have the pattern _p_ or _l_ after the speaker ID.")
elif s[12]!=".":
print("A string of length 6 is to be followed after the pattern '_l_' or '_p_'.")
elif str(s[-4::1])!=".wav":
print("The filename has the extension .wav")
else:
print("The filename is in the correct format.\nThe filename is: ",s)
flag=0

Pseudocode:

47
1. Print the conventions of the filename. i. If not, print an error message.
d. Check if the next two digits are in the range 02-55:
i. If not, print an error message.
e. Check if the pattern after the speaker ID is either '_p_' or '_l_':
2. Set flag to 1 to start the loop.
3. While flag is 1:
a. Prompt the user to enter the filename.
b. Print the segments of the filename for debugging.
c. Check if the filename starts with 's':

i. If not, print an error message.


f. Check if there is a string of length 6 after the pattern:
i. If not, print an error message.
g. Check if the filename ends with '.wav':
i. If not, print an error message.
h. If all checks pass, print that the filename is in the correct format.
4. Set flag to 0 to end the loop.

Output:
The conventions of file name:
1. The first three characters in the filename should specify specify the speaker id.
2. The file name should begin with ‘s’. ‘s’ refers to the speaker.
3. Next two digits are in the range 02-55, to uniquely identify a speaker.
4. The first three characters must be followed by either of these 2 patterns, _p_ or _l_ and
followed by a string of length 6.
5. If the filename has the pattern _p_, then display them.
6. If the filename has the pattern _l_, then display them.
7. The filename has the extension .wav
8. If the filename doesn’t follow the above said rules, print them as invalid.
Enter the filename: s56_p_ammapa.wav
The digits in the speaker id are supposed to be within the range 02-55, to uniquely identify
a speaker.
Enter the filename: s09ihnm.wav

48
The filename must have the pattern _p_ or _l_ after the speaker ID.

Learning Outcomes:
i) This program has taught me to incorporate string operations with the programming logic.
ii) In this program, string slicing has played a major role in the solution.

49
Assignment 8: Programs using lists and tuples

Name: T. Sri Subhiksha


Class: S-03
Dept: IT

1) Aim:
The aim of this program is to create a comprehensive Python application that
manages a student gradebook.

Program:
class Student:
def __init__(self, name, student_id, grades):
self.name = name
self.student_id = student_id
self.grades = grades

def average_grade(self):
return sum(self.grades) / len(self.grades) if self.grades else 0.0

def display_student(student):
print(f"{student.name}\t{student.student_id}\t{', '.join(map(str, student.grades))}\
t{student.average_grade():.2f}")

def display_gradebook(students):
print(f"{'Name':<10}{'Student ID':<10}{'Grades':<20}{'Average Grade':<15}")
for student in students:
display_student(student)

gradebook = [
Student("Alice", "S001", [85, 90, 78]),
Student("Bob", "S002", [75, 80, 88]),
Student("Charlie", "S003", [90, 92, 95])
]

def add_student(name, student_id, grades):


50
gradebook.append(Student(name, student_id, grades))
print("New student added!")

def update_grades(student_id, grades):


for student in gradebook:
if student.student_id == student_id:
student.grades = grades
print("Student grades updated!")
return
print(f"Student with ID {student_id} not found!")

def remove_student(student_id):
global gradebook
gradebook = [student for student in gradebook if student.student_id != student_id]
print("Student removed successfully!")

def calculate_average_grade(student_id):
for student in gradebook:
if student.student_id == student_id:
print(f"Average grade for {student.name}: {student.average_grade():.2f}")
return
print(f"Student with ID {student_id} not found!")

def display_subset(start_index, end_index):


for student in gradebook[start_index:end_index+1]:
display_student(student)

print("Initial Gradebook:")
display_gradebook(gradebook)
add_student("David", "S004", [88, 92, 85])
update_grades("S002", [80, 85, 90])
remove_student("S001")
calculate_average_grade("S003")
display_subset(0, 1)
print("\nUpdated Gradebook:")
display_gradebook(gradebook)

Pseudocode:
Class Student:
Method __init__(name, student_id, grades):
51
Initialize student name, student ID, and grades

Method average_grade():
Calculate and return the average grade

Function display_student(student):
Print student details (name, ID, grades, average grade)

Function display_gradebook(students):
Print header for gradebook
For each student in students:
Call display_student(student)

Initialize gradebook with three students

Function add_student(name, student_id, grades):


Append a new Student to the gradebook
Print "New student added!"

Function update_grades(student_id, grades):


For each student in gradebook:
If student_id matches:
Update student's grades
Print "Student grades updated!"
Return
Print "Student with ID not found!"

Function remove_student(student_id):
Remove student with matching student_id from gradebook
Print "Student removed successfully!"

Function calculate_average_grade(student_id):
For each student in gradebook:
If student_id matches:
Print average grade
Return
Print "Student with ID not found!"

Function display_subset(start_index, end_index):


For each student in the subset of gradebook:
52
Call display_student(student)

Print "Initial Gradebook:"


Call display_gradebook(gradebook)
Call add_student("David", "S004", [88, 92, 85])
Call update_grades("S002", [80, 85, 90])
Call remove_student("S001")
Call calculate_average_grade("S003")
Call display_subset(0, 1)

Print "Updated Gradebook:"


Call display_gradebook(gradebook)

Output:
Initial Gradebook:
Name Student ID Grades Average Grade
Alice S001 85, 90, 78 84.33
Bob S002 75, 80, 88 81.00
Charlie S003 90, 92, 95 92.33
New student added!
Student grades updated!
Student removed successfully!
Average grade for Charlie: 92.33
Bob S002 80, 85, 90 85.00
Charlie S003 90, 92, 95 92.33

Updated Gradebook:
Name Student ID Grades Average Grade
Bob S002 80, 85, 90 85.00
Charlie S003 90, 92, 95 92.33
David S004 88, 92, 85 88.33

Learning Objectives:
 Understand how to define and manipulate data structures in Python, such as lists and
classes.
 Implement basic operations on lists, including adding, updating, and removing
elements.

53
 Learn how to calculate averages and perform basic arithmetic operations on list
elements.

2)
Aim:
The aim of this program is to create a Python application that efficiently manages a
product catalog.

Program:
def display_catalog(products):
print(f"{'Name':<10}{'Price':<10}{'Description':<50}")
for product in products:
name, price, description = product
print(f"{name:<10}{price:<10}{description:<50}")

def search_products(products, search_term):


results = [product for product in products if search_term.lower() in
product[0].lower() or search_term.lower() in product[2].lower()]
return results

def sort_products_by_price(products):
return sorted(products, key=lambda product: product[1])

def add_product(products, name, price, description):


products.append((name, price, description))
print("New product added!")

def update_product(products, name, field, new_value):


for i, product in enumerate(products):
if product[0] == name:
if field == "name":
products[i] = (new_value, product[1], product[2])
elif field == "price":
products[i] = (product[0], new_value, product[2])
elif field == "description":
products[i] = (product[0], product[1], new_value)
print("Product updated!")
54
return
print("Product not found!")

products = []
num_products = int(input("Enter the number of products you want to add: "))
for _ in range(num_products):
name = input("Enter product name: ")
price = float(input("Enter product price: "))
description = input("Enter product description: ")
products.append((name, price, description))

name = input("Enter a new product name: ")


price = float(input("Enter the new product price: "))
description = input("Enter the new product description: ")
add_product(products, name, price, description)

print("\nProduct Information:")
display_catalog(products)

search_term = input("\nEnter a search term (name or description) to search for


products: ")
results = search_products(products, search_term)
print("Search Results:")
display_catalog(results)

sorted_products = sort_products_by_price(products)
print("\nSorted Product Catalog by Price:")
display_catalog(sorted_products)

name = input("\nEnter the product name you want to update: ")


new_price = float(input("Enter updated Price: "))
update_product(products, name, "price", new_price)

print("\nUpdated Product Information:")


display_catalog(products)

Pseudocode:
Define function display_catalog(products):
55
Print headers for product catalog (Name, Price, Description)
For each product in products:
Extract name, price, description from product
Print product details

Define function search_products(products, search_term):


Initialize results as an empty list
For each product in products:
If search_term is in product name or description:
Add product to results
Return results

Define function sort_products_by_price(products):


Return products sorted by price in ascending order

Define function add_product(products, name, price, description):


Append (name, price, description) tuple to products
Print "New product added!"

Define function update_product(products, name, field, new_value):


For each product in products with index i:
If product name matches:
If field is "name":
Update product name
Else if field is "price":
Update product price
Else if field is "description":
Update product description
Print "Product updated!"
Return
Print "Product not found!"

Initialize products as an empty list

Input number of products to add (num_products)


For num_products times:
Input product name, price, description
Add (name, price, description) tuple to products

Input new product name, price, description


56
Call add_product with products, new product name, price, description

Print "Product Information:"


Call display_catalog with products

Input search term


Call search_products with products and search term
Print "Search Results:"
Call display_catalog with search results

Call sort_products_by_price with products


Print "Sorted Product Catalog by Price:"
Call display_catalog with sorted products

Input product name to update, field to update, and new value


Call update_product with products, name, field, and new value

Print "Updated Product Information:"


Call display_catalog with products

Output:
Enter the number of products you want to add: 3
Enter product name: Pen
Enter product price: 25
Enter product description: Sleek nib
Enter product name: Pencil
Enter product price: 4
Enter product description: HB pencil
Enter product name: A4
Enter product price: 3
Enter product description: 7 GSM
Enter a new product name: Cup
Enter the new product price: 40
Enter the new product description: Holds juice
New product added!

Product Information:
Name Price Description
Pen 25.0 Sleek nib
Pencil 4.0 HB pencil
57
A4 3.0 7 GSM
Cup 40.0 Holds juice

Enter a search term (name or description) to search for products: GSM


Search Results:
Name Price Description
A4 3.0 7 GSM

Sorted Product Catalog by Price:


Name Price Description
A4 3.0 7 GSM
pencil 4.0 HB pencil
Pen 25.0 Sleek nib
Cup 40.0 Holds juice

Enter the product name you want to update: pencil


Enter updated Price: 6
Product updated!

Updated Product Information:


Name Price Description
Pen 25.0 Sleek nib
pencil 6.0 HB pencil
A4 3.0 7 GSM
Cup 40.0 Holds juice

Learning objectives:
 Understand the concept of tuples and lists in Python and how to store data using
these structures.
 Learn to perform CRUD (Create, Read, Update, Delete) operations on a list of
tuples.
 Implement search functionality to filter data based on user input.

UGE3188 PROBLEM SOLVING AND PYTHON PROGRAMMING


Assignment 9: Program using Dictionaries

58
Name: Sri Subhiksha. T
Class: S03

1) Aim:
To develop a program that simulates a comprehensive zoo management system
using dictionaries to store various information about animals, staff, visitors, and
operations.

Program:

# Zoo Management System

# Initialize the Animal Inventory


animal_inventory = {}

# Function to add a new animal


def add_animal():
animal_id = input("Enter animal ID: ")
species = input("Enter species: ")
age = input("Enter age: ")
health_status = input("Enter health status: ")
enclosure = input("Enter enclosure: ")

animal_inventory[animal_id] = {
"species": species,
"age": age,
"health_status": health_status,
"enclosure": enclosure
}
print(f"Animal {animal_id} added to the inventory.")

# Function to update an animal's health status


def update_health_status():
animal_id = input("Enter animal ID to update: ")
if animal_id in animal_inventory:
new_health_status = input("Enter new health status: ")
animal_inventory[animal_id]["health_status"] = new_health_status
print(f"Animal {animal_id}'s health status updated.")
else:
59
print(f"Animal {animal_id} not found in the inventory.")

# Function to transfer an animal to a different enclosure


def transfer_animal():
animal_id = input("Enter animal ID to transfer: ")
if animal_id in animal_inventory:
new_enclosure = input("Enter new enclosure: ")
animal_inventory[animal_id]["enclosure"] = new_enclosure
print(f"Animal {animal_id} transferred to enclosure {new_enclosure}.")
else:
print(f"Animal {animal_id} not found in the inventory.")

# Function to display all animals with their details


def display_animals():
if animal_inventory:
for animal_id, details in animal_inventory.items():
print(f"Animal ID: {animal_id}")
print(f" Species: {details['species']}")
print(f" Age: {details['age']}")
print(f" Health Status: {details['health_status']}")
print(f" Enclosure: {details['enclosure']}")
print("-" * 20)
else:
print("No animals in the inventory.")

# Main menu
def main():
while True:
print("Zoo Management System")
print("1. Add a new animal")
print("2. Update an animal's health status")
print("3. Transfer an animal to a different enclosure")
print("4. Display all animals")
print("5. Exit")

choice = input("Enter your choice: ")

if choice == "1":
add_animal()
elif choice == "2":

60
update_health_status()
elif choice == "3":
transfer_animal()
elif choice == "4":
display_animals()
elif choice == "5":
print("Exiting the Zoo Management System.")
break
else:
print("Invalid choice. Please try again.")

# Run the main menu


main()

Pseudocode:

Initialize an empty dictionary 'animal_inventory'

Function add_animal():
Prompt user to enter 'animal_id'
Prompt user to enter 'species'
Prompt user to enter 'age'
Prompt user to enter 'health_status'
Prompt user to enter 'enclosure'

Add new animal to 'animal_inventory' dictionary with the provided details

Function update_health_status():
Prompt user to enter 'animal_id'
If 'animal_id' exists in 'animal_inventory':
Prompt user to enter new 'health_status'
Update the 'health_status' of the animal in the 'animal_inventory' dictionary
Else:
Display message: "Animal not found in the inventory"

Function transfer_animal():
Prompt user to enter 'animal_id'
If 'animal_id' exists in 'animal_inventory':
Prompt user to enter new 'enclosure'
Update the 'enclosure' of the animal in the 'animal_inventory' dictionary
61
Else:
Display message: "Animal not found in the inventory"

Function display_animals():
If 'animal_inventory' is not empty:
For each 'animal_id' in 'animal_inventory':
Display 'animal_id', 'species', 'age', 'health_status', 'enclosure'
Else:
Display message: "No animals in the inventory"

Function main():
While True:
Display menu with options:
1. Add a new animal
2. Update an animal's health status
3. Transfer an animal to a different enclosure
4. Display all animals
5. Exit

Prompt user to enter their choice

If choice is "1":
Call add_animal()
Else If choice is "2":
Call update_health_status()
Else If choice is "3":
Call transfer_animal()
Else If choice is "4":
Call display_animals()
Else If choice is "5":
Display message: "Exiting the Zoo Management System"
Break
Else:
Display message: "Invalid choice. Please try again."

Call main() to run the program

Output:
Zoo Management System
62
1. Add a new animal
2. Update an animal's health status
3. Transfer an animal to a different enclosure
4. Display all animals
5. Exit
Enter your choice: 1
Enter animal ID: Tgr
Enter species: Tiger
Enter age: 2
Enter health status: Good
Enter enclosure: Tiger park
Animal Tgr added to the inventory.
Zoo Management System
1. Add a new animal
2. Update an animal's health status
3. Transfer an animal to a different enclosure
4. Display all animals
5. Exit
Enter your choice: 1
Enter animal ID: Pck
Enter species: Peacock
Enter age: 4
Enter health status: Critical
Enter enclosure: VET Hospital
Animal Pck added to the inventory.
Zoo Management System
1. Add a new animal
2. Update an animal's health status
63
3. Transfer an animal to a different enclosure
4. Display all animals
5. Exit
Enter your choice: 4
Animal ID: Tgr
Species: Tiger
Age: 2
Health Status: Good
Enclosure: Tiger park
--------------------
Animal ID: Pck
Species: Peacock
Age: 4
Health Status: Critical
Enclosure: VET Hospital
--------------------
Zoo Management System
1. Add a new animal
2. Update an animal's health status
3. Transfer an animal to a different enclosure
4. Display all animals
5. Exit
Enter your choice: 2
Enter animal ID to update: Pck
Enter new health status: Healthy
Animal Pck's health status updated.
Zoo Management System
1. Add a new animal
64
2. Update an animal's health status
3. Transfer an animal to a different enclosure
4. Display all animals
5. Exit
Enter your choice: 4
Animal ID: Tgr
Species: Tiger
Age: 2
Health Status: Good
Enclosure: Tiger park
--------------------
Animal ID: Pck
Species: Peacock
Age: 4
Health Status: Healthy
Enclosure: VET Hospital
--------------------
Zoo Management System
1. Add a new animal
2. Update an animal's health status
3. Transfer an animal to a different enclosure
4. Display all animals
5. Exit
Enter your choice: 3
Enter animal ID to transfer: Tgr
Enter new enclosure: Zone 4
Animal Tgr transferred to enclosure Zone 4.
Zoo Management System
65
1. Add a new animal
2. Update an animal's health status
3. Transfer an animal to a different enclosure
4. Display all animals
5. Exit
Enter your choice: 4
Animal ID: Tgr
Species: Tiger
Age: 2
Health Status: Good
Enclosure: Zone 4
--------------------
Animal ID: Pck
Species: Peacock
Age: 4
Health Status: Healthy
Enclosure: VET Hospital
--------------------
Zoo Management System
1. Add a new animal
2. Update an animal's health status
3. Transfer an animal to a different enclosure
4. Display all animals
5. Exit
Enter your choice: 5
Exiting the Zoo Management System.

66
Learning Objectives
o Learn how to use dictionaries to store and manage data.
o Understand how to add, update, and retrieve values from a dictionary.
o Understand the importance of breaking a program into smaller, manageable
functions.
o Learn how to define and call functions to perform specific tasks.

2) Aim:
To develop a program that simulates a social media platform.

Pseudocode:
Initialize an empty dictionary 'users'
Function add_user(username, is_private):
Add new user with 'username' to 'users' dictionary with initial values
- "following": []
- "followers": []
- "blocked": []
- "private account": is_private
- "follow requests": []

Function add_follower(user, target_user):


If target_user exists in 'users' and user exists in 'users':
If user is not in target_user's "blocked" list:
If target_user's "private account" is True:
Add user to target_user's "follow requests"
Else:
Add user to target_user's "followers"
Add target_user to user's "following"
67
Function remove_follower(user, target_user):
If target_user exists in 'users' and user exists in 'users':
Remove target_user from user's "following" list
Remove user from target_user's "followers" list

Function accept_follow_request(user, requester):


If user exists in 'users' and requester exists in 'users':
If requester is in user's "follow requests":
Remove requester from user's "follow requests"
Add requester to user's "followers"
Add user to requester's "following"

Function reject_follow_request(user, requester):


If user exists in 'users' and requester exists in 'users':
If requester is in user's "follow requests":
Remove requester from user's "follow requests"

Function block_user(user, target_user):


If user exists in 'users' and target_user exists in 'users':
Add target_user to user's "blocked" list
Remove target_user from user's "followers" list
Remove user from target_user's "following" list

Function view_followers(user):
If user exists in 'users':
Display the list of user's "followers"

68
Function view_mutual_followers(user):
If user exists in 'users':
For each follower in user's "followers":
If follower is also in user's "following":
Display follower

Function get_number_of_followers(user):
If user exists in 'users':
Return the number of followers in user's "followers"

Function suggest_users_to_follow(user):
If user exists in 'users':
Initialize an empty list 'suggestions'
For each follower in user's "followers":
For each person follower is following:
If person is not user and not already followed by user:
Add person to 'suggestions'
Display 'suggestions'

Function main():
While True:
Display menu with options:
1. Add a user
2. Add a follower
3. Remove a follower
4. Accept follow request
5. Reject follow request
6. Block a user
69
7. View followers
8. View mutual followers
9. Get number of followers
10. Suggest users to follow
11. Exit

Prompt user to enter their choice

Execute corresponding function based on the user's choice

Call main() to run the program

Program:
# Dictionary to store user data
users = {}

def add_user(username, private_account=False):


"""Add a new user to the platform."""
if username in users:
print(f"User '{username}' already exists.")
else:
users[username] = {
"following": [],
"followers": [],
"blocked": [],
"private account": private_account,
"follow requests": []
}
70
print(f"User '{username}' has been added to the platform.")

def add_follower(target_user, follower):


"""Add a follower to a user."""
if target_user not in users:
print(f"Target user '{target_user}' does not exist.")
return

if follower not in users:


print(f"Follower '{follower}' does not exist.")
return

if target_user == follower:
print("You cannot follow yourself.")
return

if follower in users[target_user]["blocked"]:
print(f"User '{follower}' is blocked by '{target_user}' and cannot follow.")
return

if users[target_user]["private account"]:
# Send a follow request
if follower not in users[target_user]["follow requests"]:
users[target_user]["follow requests"].append(follower)
print(f"Follow request sent to '{target_user}' from '{follower}'.")
else:
print(f"Follow request from '{follower}' already exists.")
else:
71
# Directly follow the user
if follower not in users[target_user]["followers"]:
users[target_user]["followers"].append(follower)
users[follower]["following"].append(target_user)
print(f"'{follower}' is now following '{target_user}'.")

def remove_follower(target_user, follower):


"""Remove a follower from a user."""
if target_user not in users:
print(f"Target user '{target_user}' does not exist.")
return

if follower not in users:


print(f"Follower '{follower}' does not exist.")
return

if follower in users[target_user]["followers"]:
users[target_user]["followers"].remove(follower)
users[follower]["following"].remove(target_user)
print(f"'{follower}' has unfollowed '{target_user}'.")
else:
print(f"'{follower}' is not following '{target_user}'.")

def accept_follow_request(target_user, follower):


"""Accept a follow request from a user."""
if target_user not in users:
print(f"Target user '{target_user}' does not exist.")
return
72
if follower not in users:
print(f"Follower '{follower}' does not exist.")
return

if follower not in users[target_user]["follow requests"]:


print(f"No follow request from '{follower}' to '{target_user}'.")
return

users[target_user]["follow requests"].remove(follower)
users[target_user]["followers"].append(follower)
users[follower]["following"].append(target_user)
print(f"Follow request from '{follower}' to '{target_user}' accepted.")

def reject_follow_request(target_user, follower):


"""Reject a follow request from a user."""
if target_user not in users:
print(f"Target user '{target_user}' does not exist.")
return

if follower not in users:


print(f"Follower '{follower}' does not exist.")
return

if follower not in users[target_user]["follow requests"]:


print(f"No follow request from '{follower}' to '{target_user}'.")
return

73
users[target_user]["follow requests"].remove(follower)
print(f"Follow request from '{follower}' to '{target_user}' rejected.")

def block_user(target_user, blocker):


"""Block a user to prevent them from following or interacting."""
if target_user not in users:
print(f"Target user '{target_user}' does not exist.")
return

if blocker not in users:


print(f"Blocker '{blocker}' does not exist.")
return

if blocker == target_user:
print("You cannot block yourself.")
return

if target_user not in users[blocker]["blocked"]:


users[blocker]["blocked"].append(target_user)
if target_user in users[blocker]["following"]:
users[blocker]["following"].remove(target_user)
if target_user in users[blocker]["followers"]:
users[blocker]["followers"].remove(target_user)
print(f"'{target_user}' has been blocked by '{blocker}'.")
else:
print(f"'{target_user}' is already blocked by '{blocker}'.")

def view_followers(target_user):
74
"""View a user's followers."""
if target_user not in users:
print(f"User '{target_user}' does not exist.")
return
print(f"'{target_user}' has the following followers: {users[target_user]['followers']}")

def view_mutual_followers(user1, user2):


"""View mutual followers between two users."""
if user1 not in users or user2 not in users:
print("One or both users do not exist.")
return
mutual = set(users[user1]['followers']).intersection(users[user2]['followers'])
print(f"Mutual followers between '{user1}' and '{user2}': {mutual}")

def get_number_of_followers(target_user):
"""Get the number of followers a user has."""
if target_user not in users:
print(f"User '{target_user}' does not exist.")
return
return len(users[target_user]['followers'])

def suggest_users_to_follow(target_user):
"""Suggest users to follow based on mutual follows or common connections."""
if target_user not in users:
print(f"User '{target_user}' does not exist.")
return

mutual_suggestions = set()
75
for follower in users[target_user]['followers']:
mutual_suggestions.update(set(users[follower]['followers']))

# Remove already followed or blocked users from suggestions


suggestions = mutual_suggestions.difference(users[target_user]['following'])
suggestions = suggestions.difference(users[target_user]['blocked'])

print(f"Suggested users for '{target_user}' to follow: {suggestions}")

def print_menu():
"""Print the menu for the user to select tasks."""
print("\nSocial Media Platform Menu")
print("1. Add a new user")
print("2. Add a follower")
print("3. Remove a follower")
print("4. Accept follow request")
print("5. Reject follow request")
print("6. Block a user")
print("7. View followers")
print("8. View mutual followers")
print("9. Get number of followers")
print("10. Suggest users to follow")
print("11. Exit")

def main():
while True:
print_menu()
choice = input("Please choose an option (1-11): ")
76
if choice == "1":
username = input("Enter the username to add: ")
private = input("Is the account private? (yes/no): ").lower() == "yes"
add_user(username, private)
elif choice == "2":
target_user = input("Enter the username to follow: ")
follower = input("Enter your username: ")
add_follower(target_user, follower)
elif choice == "3":
target_user = input("Enter the username to unfollow: ")
follower = input("Enter your username: ")
remove_follower(target_user, follower)
elif choice == "4":
target_user = input("Enter the username to accept the follow request for: ")
follower = input("Enter the username who sent the follow request: ")
accept_follow_request(target_user, follower)
elif choice == "5":
target_user = input("Enter the username to reject the follow request for: ")
follower = input("Enter the username who sent the follow request: ")
reject_follow_request(target_user, follower)
elif choice == "6":
target_user = input("Enter the username to block: ")
blocker = input("Enter your username: ")
block_user(target_user, blocker)
elif choice == "7":
target_user = input("Enter the username to view followers: ")
view_followers(target_user)
77
elif choice == "8":
user1 = input("Enter the first username: ")
user2 = input("Enter the second username: ")
view_mutual_followers(user1, user2)
elif choice == "9":
target_user = input("Enter the username to get the number of followers: ")
num_followers = get_number_of_followers(target_user)
if num_followers is not None:
print(f"{target_user} has {num_followers} followers.")
elif choice == "10":
target_user = input("Enter the username to get suggestions for: ")
suggest_users_to_follow(target_user)
elif choice == "11":
print("Exiting the program. Goodbye!")
break
else:
print("Invalid choice. Please try again.")

# Run the program


main()

Output:
Social Media Platform Menu
1. Add a new user
2. Add a follower
3. Remove a follower
4. Accept follow request
5. Reject follow request
78
6. Block a user
7. View followers
8. View mutual followers
9. Get number of followers
10. Suggest users to follow
11. Exit
Please choose an option (1-11): 1
Enter the username to add: sri_26
Is the account private? (yes/no): no
User 'sri_26' has been added to the platform.

Social Media Platform Menu


1. Add a new user
2. Add a follower
3. Remove a follower
4. Accept follow request
5. Reject follow request
6. Block a user
7. View followers
8. View mutual followers
9. Get number of followers
10. Suggest users to follow
11. Exit
Please choose an option (1-11): 1
Enter the username to add: subi_26
Is the account private? (yes/no): yes
User 'subi_26' has been added to the platform.

79
Social Media Platform Menu
1. Add a new user
2. Add a follower
3. Remove a follower
4. Accept follow request
5. Reject follow request
6. Block a user
7. View followers
8. View mutual followers
9. Get number of followers
10. Suggest users to follow
11. Exit
Please choose an option (1-11): 2
Enter the username to follow: sri_26
Enter your username: subi_26
'subi_26' is now following 'sri_26'.

Social Media Platform Menu


1. Add a new user
2. Add a follower
3. Remove a follower
4. Accept follow request
5. Reject follow request
6. Block a user
7. View followers
8. View mutual followers
9. Get number of followers
10. Suggest users to follow
80
11. Exit
Please choose an option (1-11): 1
Enter the username to add: ash.9260
Is the account private? (yes/no): yes
User 'ash.9260' has been added to the platform.

Social Media Platform Menu


1. Add a new user
2. Add a follower
3. Remove a follower
4. Accept follow request
5. Reject follow request
6. Block a user
7. View followers
8. View mutual followers
9. Get number of followers
10. Suggest users to follow
11. Exit
Please choose an option (1-11): 2
Enter the username to follow: sri_26
Enter your username: ash.9260
'ash.9260' is now following 'sri_26'.

Social Media Platform Menu


1. Add a new user
2. Add a follower
3. Remove a follower
4. Accept follow request
81
5. Reject follow request
6. Block a user
7. View followers
8. View mutual followers
9. Get number of followers
10. Suggest users to follow
11. Exit
Please choose an option (1-11): 4
Enter the username to accept the follow request for: ash.9260
Enter the username who sent the follow request: ash.9260
No follow request from 'ash.9260' to 'ash.9260'.

Social Media Platform Menu


1. Add a new user
2. Add a follower
3. Remove a follower
4. Accept follow request
5. Reject follow request
6. Block a user
7. View followers
8. View mutual followers
9. Get number of followers
10. Suggest users to follow
11. Exit
Please choose an option (1-11): 11

Learning Objectives:
82
 Learn how to use dictionaries to store and manage data.
 Understand how to add, update, and retrieve values from a dictionary.
 Learn how to prompt the user for input and handle user responses.
 Understand how to validate user input and provide appropriate feedback.

83
UGE3188 PROBLEM SOLVING AND PYTHON PROGRAMMING
Assignment 10: Programs using Files

1)
Aim
To implement a simple Student Attendance Management System using Python that allows a
teacher to manage student attendance records by utilizing file operations. The system will
enable marking attendance, saving attendance records, viewing past attendance records,
and adding/removing students from the list.

Pseudocode
1. Student List:
o Create students.txt file containing student names.
o Read the names from the students.txt file at startup.
2. Mark Attendance:
o Prompt the teacher to mark attendance for each student ("Y" for present, "N"
for absent).
o Store the attendance status for each student in a dictionary.
3. Save Attendance:
o Save the attendance record to attendance.txt after marking attendance.
o Include the date and each student's attendance status.
4. View Attendance Records:
o Read the attendance.txt file.
o Display attendance for each recorded day.
5. Add/Remove Students:
o Allow the teacher to add/remove students from students.txt.
o Update the file accordingly when students are added/removed.

Program:

84
import os
from datetime
import datetime

# Function to read students from students.txt


def read_students():
with open("students.txt", "r") as file:
students = [line.strip() for line in file.readlines()]
return students

# Function to add a student to students.txt


def add_student(name):
with open("students.txt", "a") as file:
file.write(name + "\n")
print(f"Student '{name}' added successfully.")

# Function to remove a student from students.txt


def remove_student(name):
students = read_students()
if name in students:
students.remove(name)
with open("students.txt", "w") as file:
for student in students:
file.write(student + "\n")
print(f"Student '{name}' removed successfully.")
else:
print(f"Student '{name}' not found.")

85
# Function to mark attendance
def mark_attendance():
students = read_students()
attendance = {}
for student in students:
status = input(f"Mark attendance for {student} (Y/N): ").strip().upper()
if status == "Y":
attendance[student] = "Present"
else:
attendance[student] = "Absent"
save_attendance(attendance)

# Function to save attendance to attendance.txt


def save_attendance(attendance):
date = datetime.now().strftime("%Y-%m-%d")
with open("attendance.txt", "a") as file:
file.write(f"Date: {date}\n")
for student, status in attendance.items():
file.write(f"{student}: {status}\n")
file.write("\n")
print("Attendance saved successfully.")

# Function to view attendance records


def view_attendance_records():
if os.path.exists("attendance.txt"):
with open("attendance.txt", "r") as file:
print(file.read())
else:
86
print("No attendance records found.")

# Main function
def main():
while True:
print("\nStudent Attendance Management System")
print("1. Mark Attendance")
print("2. View Attendance Records")
print("3. Add Student")
print("4. Remove Student")
print("5. Exit")

choice = input("Enter your choice: ").strip()


if choice == "1":
mark_attendance()
elif choice == "2":
view_attendance_records()
elif choice == "3":
name = input("Enter the name of the student to add: ").strip()
add_student(name)
elif choice == "4":
name = input("Enter the name of the student to remove: ").strip()
remove_student(name)
elif choice == "5":
print("Exiting the system. Goodbye!")
break
else:
print("Invalid choice. Please try again.")

87
if __name__ == "__main__":
main()

Output:
Student Attendance Management System
1. Mark Attendance
2. View Attendance Records
3. Add Student
4. Remove Student
5. Exit
Enter your choice: 3
Enter the name of the student to add: Abi
Student 'Abi' added successfully.

Student Attendance Management System


1. Mark Attendance
2. View Attendance Records
3. Add Student
4. Remove Student
5. Exit
Enter your choice: 3
Enter the name of the student to add: Suji
Student 'Suji' added successfully.

Student Attendance Management System


1. Mark Attendance
2. View Attendance Records
88
3. Add Student
4. Remove Student
5. Exit
Enter your choice: 3
Enter the name of the student to add: Subi
Student 'Subi' added successfully.

Student Attendance Management System


1. Mark Attendance
2. View Attendance Records
3. Add Student
4. Remove Student
5. Exit
Enter your choice: 1
Mark attendance for Abi (Y/N): Y
Mark attendance for Suji (Y/N): Y
Mark attendance for Subi (Y/N): N
Attendance saved successfully.

Student Attendance Management System


1. Mark Attendance
2. View Attendance Records
3. Add Student
4. Remove Student
5. Exit
Enter your choice: 3
Enter the name of the student to add: Ava
Student 'Ava' added successfully.
89
Student Attendance Management System
1. Mark Attendance
2. View Attendance Records
3. Add Student
4. Remove Student
5. Exit
Enter your choice: 1
Mark attendance for Abi (Y/N): Y
Mark attendance for Suji (Y/N): Y
Mark attendance for Subi (Y/N): Y
Mark attendance for Ava (Y/N): N
Attendance saved successfully.

Student Attendance Management System


1. Mark Attendance
2. View Attendance Records
3. Add Student
4. Remove Student
5. Exit
Enter your choice: 2
Date: 2024-12-14
Abi: Present
Suji: Present
Subi: Absent

Date: 2024-12-14
Abi: Present
90
Suji: Present
Subi: Present
Ava: Absent

Student Attendance Management System


1. Mark Attendance
2. View Attendance Records
3. Add Student
4. Remove Student
5. Exit
Enter your choice: 4
Enter the name of the student to remove: Subi
Student 'Subi' removed successfully.

Student Attendance Management System


1. Mark Attendance
2. View Attendance Records
3. Add Student
4. Remove Student
5. Exit
Enter your choice: 2
Date: 2024-12-14
Abi: Present
Suji: Present
Subi: Absent

91
Date: 2024-12-14
Abi: Present
Suji: Present
Subi: Present
Ava: Absent

Student Attendance Management System


1. Mark Attendance
2. View Attendance Records
3. Add Student
4. Remove Student
5. Exit
Enter your choice: 4
Enter the name of the student to remove: Subi
Student 'Subi' not found.

Student Attendance Management System


1. Mark Attendance
2. View Attendance Records
3. Add Student
4. Remove Student
5. Exit
Enter your choice: 2
Date: 2024-12-14
Abi: Present
Suji: Present
92
Subi: Absent

Date: 2024-12-14
Abi: Present
Suji: Present
Subi: Present
Ava: Absent

Student Attendance Management System


1. Mark Attendance
2. View Attendance Records
3. Add Student
4. Remove Student
5. Exit
Enter your choice: 5
Exiting the system. Goodbye!

Learning Outcomes
1. I gained an understanding of reading from and writing to text files in Python.
2. I learned to store and retrieve data using dictionaries.
3. Understood how to work with date and time in Python.
4. I improved my skills in handling user inputs and performing basic validations.

2)
Aim
93
To implement a simple Movie Recommendation System using Python that allows users to
manage their favorite movies. The system will store and retrieve movie information using
file operations and handle potential errors during file operations using exception handling

Pseudocode
1. Movie List:
o Create a movies.txt file containing a list of movies (each line with title, genre,
and release year).
o Read the movies.txt file at startup to load the list of available movies.
2. Add Movie:
o Prompt the user to add a new movie (title, genre, release year).
o Append the new movie details to the movies.txt file.
3. Remove Movie:
o Allow the user to remove a movie by its title.
o Search for the movie in the movies.txt file and remove it if found.
4. View Movies:
o Read from the movies.txt file.
o Display each movie's details.
5. Recommend Movie:
o Allow the user to get a movie recommendation based on a selected genre.

Program:
import os
# Function to read movies from movies.txt
def read_movies():
try:
with open("movies.txt", "r") as file:
movies = [line.strip().split(",") for line in file.readlines()]
return movies
94
except FileNotFoundError:
print("The movies.txt file does not exist. Creating a new one...")
open("movies.txt", "w").close()
return []

# Function to add a movie to movies.txt


def add_movie(title, genre, year):
try:
with open("movies.txt", "a") as file:
file.write(f"{title},{genre},{year}\n")
print(f"Movie '{title}' added successfully.")
except Exception as e:
print(f"An error occurred while adding the movie: {e}")

# Function to remove a movie from movies.txt


def remove_movie(title):
movies = read_movies()
updated_movies = [movie for movie in movies if movie[0] != title]
if len(movies) == len(updated_movies):
print(f"Movie '{title}' not found.")
else:
try:
with open("movies.txt", "w") as file:
for movie in updated_movies:
file.write(",".join(movie) + "\n")
print(f"Movie '{title}' removed successfully.")
except Exception as e:
print(f"An error occurred while removing the movie: {e}")
95
# Function to view all movies
def view_movies():
movies = read_movies()
if movies:
print("\nList of Movies:")
for movie in movies:
print(f"Title: {movie[0]}, Genre: {movie[1]}, Year: {movie[2]}")
else:
print("No movies found.")

# Function to recommend a movie based on genre


def recommend_movie(genre):
movies = read_movies()
genre_movies = [movie for movie in movies if movie[1].lower() == genre.lower()]
if genre_movies:
recommended_movie = random.choice(genre_movies)
print(f"Recommended Movie: {recommended_movie[0]} ({recommended_movie[2]})")
else:
print(f"No movies found in the genre '{genre}'.")

# Main function
def main():
while True:
print("\nMovie Recommendation System")
print("1. Add Movie")
print("2. Remove Movie")
print("3. View Movies")
96
print("4. Recommend Movie")
print("5. Exit")

choice = input("Enter your choice: ").strip()


if choice == "1":
title = input("Enter movie title: ").strip()
genre = input("Enter movie genre: ").strip()
year = input("Enter release year: ").strip()
add_movie(title, genre, year)
elif choice == "2":
title = input("Enter the title of the movie to remove: ").strip()
remove_movie(title)
elif choice == "3":
view_movies()
elif choice == "4":
genre = input("Enter genre for recommendation: ").strip()
recommend_movie(genre)
elif choice == "5":
print("Exiting the system. Goodbye!")
break
else:
print("Invalid choice. Please try again.")

if __name__ == "__main__":
main()

Output:
Movie Recommendation System

97
1. Add Movie
2. Remove Movie
3. View Movies
4. Recommend Movie
5. Exit
Enter your choice: 1
Enter movie title: I
Enter movie genre: Thriller
Enter release year: 2015
Movie 'I' added successfully.

Movie Recommendation System


1. Add Movie
2. Remove Movie
3. View Movies
4. Recommend Movie
5. Exit
Enter your choice: 1
Enter movie title: Ayan
Enter movie genre: Action
Enter release year: 2010
Movie 'Ayan' added successfully.

Movie Recommendation System


1. Add Movie
2. Remove Movie
3. View Movies
4. Recommend Movie
98
5. Exit
Enter your choice: 1
Enter movie title: Pyaar Prema Kaadhal
Enter movie genre: Romance
Enter release year: 2019
Movie 'Pyaar Prema Kaadhal' added successfully.

Movie Recommendation System


1. Add Movie
2. Remove Movie
3. View Movies
4. Recommend Movie
5. Exit
Enter your choice: 1
Enter movie title: Kavalai vendaam
Enter movie genre: Romance
Enter release year: 2015
Movie 'Kavalai vendaam' added successfully.

Movie Recommendation System


1. Add Movie
2. Remove Movie
3. View Movies
4. Recommend Movie
5. Exit
Enter your choice: 3

List of Movies:
99
Title: I, Genre: Thriller, Year: 2010
Title: Ayan, Genre: Romance, Year: 2009
Title: Hotspot, Genre: Thought-provoking, Year: 2024
Title: Pyaar prema kaadhal, Genre: Romance, Year: 2019
Title: I, Genre: Romance, Year: Ayan
Title: I, Genre: Thriller, Year: 2015
Title: Ayan, Genre: Action, Year: 2010
Title: Pyaar Prema Kaadhal, Genre: Romance, Year: 2019
Title: Kavalai vendaam, Genre: Romance, Year: 2015

Movie Recommendation System


1. Add Movie
2. Remove Movie
3. View Movies
4. Recommend Movie
5. Exit
Enter your choice: 4
Enter genre for recommendation: Romance
Recommended Movie: Ayan (2009)

Movie Recommendation System


1. Add Movie
2. Remove Movie
3. View Movies
4. Recommend Movie
5. Exit
Enter your choice: 2
Enter the title of the movie to remove: Ayan
100
Movie 'Ayan' removed successfully.

Movie Recommendation System


1. Add Movie
2. Remove Movie
3. View Movies
4. Recommend Movie
5. Exit
Enter your choice: 3

List of Movies:
Title: I, Genre: Thriller, Year: 2010
Title: Hotspot, Genre: Thought-provoking, Year: 2024
Title: Pyaar prema kaadhal, Genre: Romance, Year: 2019
Title: I, Genre: Romance, Year: Ayan
Title: I, Genre: Thriller, Year: 2015
Title: Pyaar Prema Kaadhal, Genre: Romance, Year: 2019
Title: Kavalai vendaam, Genre: Romance, Year: 2015

Movie Recommendation System


1. Add Movie
2. Remove Movie
3. View Movies
4. Recommend Movie
5. Exit
Enter your choice: 2
Enter the title of the movie to remove: I
Movie 'I' removed successfully.
101
Movie Recommendation System
1. Add Movie
2. Remove Movie
3. View Movies
4. Recommend Movie
5. Exit
Enter your choice: 3

List of Movies:
Title: Hotspot, Genre: Thought-provoking, Year: 2024
Title: Pyaar prema kaadhal, Genre: Romance, Year: 2019
Title: Pyaar Prema Kaadhal, Genre: Romance, Year: 2019
Title: Kavalai vendaam, Genre: Romance, Year: 2015

Movie Recommendation System


1. Add Movie
2. Remove Movie
3. View Movies
4. Recommend Movie
5. Exit
Enter your choice: 5
Exiting the system. Goodbye!

Learning Outcomes
1. List and Dictionary Usage: Improved skills in using lists to store and manipulate
data.
2. Random Selection: Learned how to use the random module to make random
selections from a list.
102
3. User Interaction: Enhanced skills in designing user-friendly command-line
interfaces.
4. Menu-driven Program: Developed the ability to create a menu-driven program
with multiple functionalities.

103

You might also like