functions
functions
Scenario Description:
A Python program that helps a user manage their monthly budget. The user can add
expenses, calculate total expenses, and compare them with their monthly budget.
This scenario demonstrates the use of functions in Python for organising and
executing specific tasks.
Functions Demonstrated:
add_expense: To add an expense to the budget.
calculate_total_expenses: To sum up all expenses.
compare_with_budget: To compare total expenses with the user's budget.
Solution:
# Main program
def main():
monthly_budget = float(input("Enter your monthly budget: "))
expenses = {}
while True:
category = input("Enter the expense category (or 'done' to finish): ")
if category == 'done':
break
amount = float(input(f"Enter the amount for {category}: "))
add_expense(expenses, category, amount)
total_expenses = calculate_total_expenses(expenses)
print(f"Total Expenses: {total_expenses}")
compare_with_budget(total_expenses, monthly_budget)
Scenario Description:
A Python program for a human resources department to analyze employee
performance. The program processes a list of employee performance scores,
applying transformations and analyses using map(), filter(), and reduce(). This
scenario demonstrates the use of these functional programming concepts in Python.
Operations Demonstrated:
map(): To adjust scores based on a normalization factor.
filter(): To filter out employees who meet a certain performance threshold.
reduce(): To calculate the total of the adjusted performance scores.
Solution:
# Main program
def main():
# Original employee scores
employee_scores = [68, 75, 56, 85, 92, 58, 77, 88, 60]
Scenario Description:
A Python program simulating a basic savings account management system. The
user can deposit, withdraw, and view their balance. The scenario demonstrates the
use of local, non-local, and global variables in nested functions.
Variables Demonstrated:
Global Variable: Interest rate applicable to the savings account.
Non-Local Variable: Account balance within the outer function.
Local Variable: Amount to deposit or withdraw within the inner functions.
Solution:
# Global variable
interest_rate = 0.05 # 5% interest rate
def savings_account():
# Non-local variable
balance = 0
Scenario Description:
A Python program that processes event logs from a system. It involves a closure for
maintaining the state of log processing, a generator for iterating through the logs,
and custom iterators for different types of log analysis. This scenario demonstrates
closures, generators, and iterators.
Features Demonstrated:
Closure: To keep track of the number of logs processed.
Generator: To iterate through the logs.
Iterator: Custom iterator for filtering specific types of logs.
Solution:
def process(log):
nonlocal count
count += 1
print(f"Processing log #{count}: {log}")
def total_processed():
return count
def __next__(self):
while self.index < len(self.logs):
log = self.logs[self.index]
self.index += 1
if "ERROR" in log:
return log
raise StopIteration
# Example logs
logs = [
"INFO: User logged in",
"ERROR: Disk not found",
"INFO: File saved",
"ERROR: Connection lost"
]