Menu

Functions for Reusable Analysis

Functions for Reusable Analysis

Functions group instructions into reusable blocks. They help keep data analysis code organized and reduce repetition.

Defining and Calling a Function

Use the def keyword to define a function. Parameters allow you to pass input values, while return sends a result back to the caller.

def calculate_profit(revenue, expenses):

profit = revenue - expenses
return profit
result = calculate_profit(50000, 32000)
print("Profit:", result)

The function can be reused with different inputs without rewriting the calculation.

Functions with Default Parameters

You can provide default values for parameters that are optional.

def calculate_discount(price, discount_rate=0.10):
discount = price * discount_rate
return price - discount
print(calculate_discount(1000))       # 900.0
print(calculate_discount(1000, 0.20)) # 800.0

Returning Multiple Results

A function can return multiple values, which Python packages together as a tuple.

def analyze_sales(sales):
total = sum(sales)
average = total / len(sales)
highest = max(sales)
return total, average, highest
sales = [1200, 1500, 900, 1800]
total, average, highest = analyze_sales(sales)
print("Total:", total)
print("Average:", average)
print("Highest:", highest)

When building analytical workflows, functions can separate tasks such as calculating metrics, validating inputs, and transforming data. This makes code easier to test, maintain, and reuse.


Python for Data Science

VA

Vishalini A



Learn via Video Course

undefined Logo

NaN hrs



Get in Touch For Details