As you perform more complex analysis, you’ll write the same code repeatedly. Functions are named, reusable blocks of code that perform a specific task, helping you avoid repetition and write cleaner, more maintainable code.
def
): You define a function using the def
keyword.revenue
, expenses
).return
Statement: Sends a value back from the function, so you can use the result in other parts of your code.def get_net_profit(revenue: float) -> float:
). This improves code clarity and helps prevent bugs.Before you begin, ensure you have followed the setup instructions in the main README.md to set up your virtual environment and install the required libraries.
The script for this lesson, functions.py
, is already well-structured, with each piece of business logic encapsulated in its own function. We’ve made a minor improvement by wrapping the example usage in a main()
function, which is a standard convention.
Day_11_Functions/functions.py
. Examine the different functions like get_net_profit()
, calculate_commission()
, and format_currency()
.Coding-For-MBA
), run the script to see the functions in action:
python Day_11_Functions/functions.py
pytest tests/test_day_11.py
Commission Calculator Function:
calculate_commission
function is already created in functions.py
.my_solutions_11.py
), import this function: from Day_11_Functions.functions import calculate_commission
.Employee Bonus Eligibility Function:
is_eligible_for_bonus
function.performance_rating
and years_of_service
and print the True
/False
results.Advanced Currency Formatter:
format_currency_with_symbol(amount, symbol='$')
.symbol
parameter that defaults to '$'
.€1,250.50
if the symbol is '€'
.symbol
parameter.🎉 Great work! Functions are the key to writing clean, organized, and professional code. By packaging your logic into reusable tools, you’re moving from a simple scripter to a true programmer.
Run this lesson’s code interactively in your browser:
!!! tip “About JupyterLite” JupyterLite runs entirely in your browser using WebAssembly. No installation or server required! Note: First launch may take a moment to load.
???+ example “functions.py” View on GitHub
```python title="functions.py"
"""
Day 11: Building Reusable Business Tools with Functions (Refactored)
This script demonstrates how to define and call functions
to perform repeatable business calculations.
"""
# Adding type hints (e.g., revenue: float) makes the function's expected inputs clear.
# The "-> float" indicates that the function is expected to return a float value.
def get_net_profit(revenue: float, expenses: float) -> float:
"""Calculates the net profit from revenue and expenses."""
net_profit = revenue - expenses
return net_profit
def calculate_commission(sales_amount: float) -> float:
"""Calculates a 15% commission on a given sales amount."""
commission_rate = 0.15
commission = sales_amount * commission_rate
return commission
def is_eligible_for_bonus(performance_rating: int, years_of_service: int) -> bool:
"""
Checks if an employee is eligible for a bonus based on performance
and years of service.
"""
# Returns True if rating is 4 or 5 AND service is more than 2 years.
return performance_rating >= 4 and years_of_service > 2
def format_currency(amount: float) -> str:
"""Formats a number into a currency string (e.g., $1,234.56)."""
return f"${amount:,.2f}"
def main():
"""Main function to demonstrate the use of the business functions."""
# --- Using the Functions ---
print("--- Calculating Company-Wide Profits ---")
# Let's use our functions to analyze two different products.
product_a_revenue = 500000
product_a_expenses = 400000
product_a_profit = get_net_profit(product_a_revenue, product_a_expenses)
print(f"Product A Profit: {format_currency(product_a_profit)}")
product_b_revenue = 250000
product_b_expenses = 210000
product_b_profit = get_net_profit(product_b_revenue, product_b_expenses)
print(f"Product B Profit: {format_currency(product_b_profit)}")
total_profit = product_a_profit + product_b_profit
print(f"Total Company Profit: {format_currency(total_profit)}")
print("-" * 20)
print("--- Sales and Bonus Calculations ---")
sales_figure = 12000
commission_earned = calculate_commission(sales_figure)
print(
f"A sale of {format_currency(sales_figure)} earns a commission of {format_currency(commission_earned)}."
)
print()
# Test the bonus eligibility function with different scenarios
employee1_rating = 5
employee1_service = 3
eligibility1 = is_eligible_for_bonus(employee1_rating, employee1_service)
print(
f"Employee 1 (Rating: {employee1_rating}, Service: {employee1_service} yrs) is eligible for bonus: {eligibility1}"
)
employee2_rating = 4
employee2_service = 1
eligibility2 = is_eligible_for_bonus(employee2_rating, employee2_service)
print(
f"Employee 2 (Rating: {employee2_rating}, Service: {employee2_service} yr) is eligible for bonus: {eligibility2}"
)
print("-" * 20)
if __name__ == "__main__":
main()
```
???+ example “solutions.py” View on GitHub
```python title="solutions.py"
"""
Day 11: Solutions to Exercises
"""
# --- Exercise 1: Commission Calculator Function ---
print("--- Solution to Exercise 1 ---")
def calculate_commission(sales_amount: float) -> float:
"""
Calculates a commission of 15% of the sales amount.
Takes sales_amount as a float, returns the commission as a float.
"""
commission_rate = 0.15
return sales_amount * commission_rate
# Example usage:
sample_sale = 5000.00
commission_earned = calculate_commission(sample_sale)
print(f"A sale of ${sample_sale:,.2f} earns a commission of ${commission_earned:,.2f}.")
print("-" * 20)
# --- Exercise 2: Employee Bonus Eligibility Function ---
print("--- Solution to Exercise 2 ---")
def is_eligible_for_bonus(performance_rating: int, years_of_service: int) -> bool:
"""
Returns True if rating is 4 or 5 AND service is more than 2 years.
"""
return performance_rating >= 4 and years_of_service > 2
# Test cases:
print(
f"Rating 5, 3 years service -> Eligible? {is_eligible_for_bonus(5, 3)}"
) # Expected: True
print(
f"Rating 4, 3 years service -> Eligible? {is_eligible_for_bonus(4, 3)}"
) # Expected: True
print(
f"Rating 5, 1 year service -> Eligible? {is_eligible_for_bonus(5, 1)}"
) # Expected: False
print(
f"Rating 3, 5 years service -> Eligible? {is_eligible_for_bonus(3, 5)}"
) # Expected: False
print("-" * 20)
# --- Exercise 3: Format Currency Function ---
print("--- Solution to Exercise 3 ---")
def format_currency(number: float) -> str:
"""
Returns a string formatted as currency with a dollar sign and commas.
Example: 1250.5 -> "$1,250.50"
"""
return f"${number:,.2f}"
# Example usage:
amount1 = 1250.5
amount2 = 500
print(f"{amount1} -> {format_currency(amount1)}")
print(f"{amount2} -> {format_currency(amount2)}")
print("-" * 20)
```