0% found this document useful (0 votes)
8 views8 pages

functions

The document describes four Python programming scenarios: a personal budget planner, employee performance analysis, a savings account management system, and an event logs processing system. Each scenario demonstrates specific programming concepts such as functions, functional programming (map, filter, reduce), variable scopes (local, non-local, global), and advanced features like closures, generators, and custom iterators. The solutions provided include code implementations for each scenario, highlighting the use of Python's capabilities for practical applications.

Uploaded by

Guru Teja
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views8 pages

functions

The document describes four Python programming scenarios: a personal budget planner, employee performance analysis, a savings account management system, and an event logs processing system. Each scenario demonstrates specific programming concepts such as functions, functional programming (map, filter, reduce), variable scopes (local, non-local, global), and advanced features like closures, generators, and custom iterators. The solutions provided include code implementations for each scenario, highlighting the use of Python's capabilities for practical applications.

Uploaded by

Guru Teja
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Problem 1:

Real-Time Scenario: Personal Budget Planner

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:

# Function to add an expense


def add_expense(expenses, category, amount):
if category in expenses:
expenses[category] += amount
else:
expenses[category] = amount
print(f"Added: {amount} to {category}")

# Function to calculate total expenses


def calculate_total_expenses(expenses):
return sum(expenses.values())

# Function to compare total expenses with budget


def compare_with_budget(total_expenses, budget):
if total_expenses > budget:
print(f"You are over budget by {total_expenses - budget}")
elif total_expenses < budget:
print(f"You are under budget by {budget - total_expenses}")
else:
print("You are exactly on budget")

# 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)

# Running the main program


main()
Problem 2: (map(),filter(),reduce())

Real-Time Scenario: Employee Performance Analysis

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:

from functools import reduce

# Function to adjust scores


def adjust_score(score):
normalization_factor = 1.1
return score * normalization_factor

# Function to check if score is above a threshold


def is_score_above_threshold(score, threshold=75):
return score > threshold

# Function to add two values


def add(x, y):
return x + y

# Main program
def main():
# Original employee scores
employee_scores = [68, 75, 56, 85, 92, 58, 77, 88, 60]

# Adjust scores using map()


adjusted_scores = list(map(adjust_score, employee_scores))

# Filter scores using filter()


scores_above_threshold = list(filter(lambda score: is_score_above_threshold(score),
adjusted_scores))

# Calculate total using reduce()


total_adjusted_score = reduce(add, adjusted_scores)

print(f"Original Scores: {employee_scores}")


print(f"Adjusted Scores: {adjusted_scores}")
print(f"Scores Above Threshold: {scores_above_threshold}")
print(f"Total of Adjusted Scores: {total_adjusted_score}")

# Running the main program


main()
Problem 3: (local, non local, global, nested functions)

Real-Time Scenario: Nested Function for Savings Account

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

# Function to deposit money


def deposit():
nonlocal balance
amount = float(input("Enter the amount to deposit: ")) # Local variable
balance += amount
print(f"Deposited: ${amount:.2f}")

# Function to withdraw money


def withdraw():
nonlocal balance
amount = float(input("Enter the amount to withdraw: ")) # Local variable
if amount > balance:
print("Insufficient balance!")
else:
balance -= amount
print(f"Withdrawn: ${amount:.2f}")

# Function to display the balance


def display_balance():
# Using global variable
print(f"Current Balance: ${balance:.2f}")
print(f"Interest Rate: {interest_rate * 100}%")

# Main loop for the savings account


def manage_account():
while True:
action = input("Choose an action - Deposit (D), Withdraw (W), Balance (B), Exit (E):
").upper()
if action == 'D':
deposit()
elif action == 'W':
withdraw()
elif action == 'B':
display_balance()
elif action == 'E':
print("Exiting account management.")
break
else:
print("Invalid option. Please choose again.")

# Running the account management


manage_account()

# Creating and managing a savings account


savings_account()
Problem 4: (iterators, generators, closures)

Real-Time Scenario: Event Logs Processing System

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:

# Closure to keep track of logs count


def log_processor():
count = 0

def process(log):
nonlocal count
count += 1
print(f"Processing log #{count}: {log}")

def total_processed():
return count

return process, total_processed

# Generator to iterate through logs


def log_generator(logs):
for log in logs:
yield log

# Custom iterator for specific log analysis


class ErrorLogIterator:
def __init__(self, logs):
self.logs = logs
self.index = 0
def __iter__(self):
return self

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"
]

# Using the closure


process_log, get_total = log_processor()

# Processing logs using generator


for log in log_generator(logs):
process_log(log)

print(f"Total logs processed: {get_total()}")

# Analyzing error logs using custom iterator


error_logs = ErrorLogIterator(logs)
print("\nError Logs:")
for log in error_logs:
print(log)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy