All Python Assignment of semester 1 for ssn students
All Python Assignment of semester 1 for ssn students
PART C) Assignment
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.
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.
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.
6
c. Devise a solution and represent the same using flowchart and pseudocode. Flowchart:
Start
Calculate DPR:
DPR=APR/365
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
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
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
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
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
False False
elif age>=31
If age>=19 and age<=40
and age<=30
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.")
20
Assignment-4
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:
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.
Aim:
To write a python program to generate payroll for employees in accordance to certain
parameters given in the question.
Program:
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
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: "))
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_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
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
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.
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.
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.
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.
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.
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:
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':
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
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 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!")
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)
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!"
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 sort_products_by_price(products):
return sorted(products, key=lambda product: product[1])
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))
print("\nProduct Information:")
display_catalog(products)
sorted_products = sort_products_by_price(products)
print("\nSorted Product Catalog by Price:")
display_catalog(sorted_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
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
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.
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:
animal_inventory[animal_id] = {
"species": species,
"age": age,
"health_status": health_status,
"enclosure": enclosure
}
print(f"Animal {animal_id} added to 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")
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.")
Pseudocode:
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'
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
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."
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 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
Program:
# Dictionary to store user data
users = {}
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}'.")
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}'.")
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.")
73
users[target_user]["follow requests"].remove(follower)
print(f"Follow request from '{follower}' to '{target_user}' rejected.")
if blocker == target_user:
print("You cannot block yourself.")
return
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 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']))
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.")
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.
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'.
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
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)
# 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")
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.
Date: 2024-12-14
Abi: Present
90
Suji: Present
Subi: Present
Ava: Absent
91
Date: 2024-12-14
Abi: Present
Suji: Present
Subi: Present
Ava: Absent
Date: 2024-12-14
Abi: Present
Suji: Present
Subi: Present
Ava: Absent
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 []
# 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")
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.
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
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
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
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