Easy
  Python
    Guide
Functions
Functions in Python are reusable blocks of code that perform specific tasks. Think of them as mini-programmes within your main programme that you can call upon whenever you need them. Just like how you might have a recipe for making tea that you follow the same way each time, a function contains a set of instructions that executes the same way whenever you "call" or use it. Functions help programmers avoid writing the same code repeatedly and make programmes easier to understand, test, and maintain.
The basic structure of a Python function starts with the keyword "def", followed by the function name and parentheses. Inside the parentheses, you can specify parameters (inputs the function needs), and the function can return a result. For example, a simple function might look like: def calculate_vat(price): return price * 0.2. This function takes a price as input and returns the VAT amount. You'd call it by writing vat_amount = calculate_vat(100), which would give you 20.
In data analysis roles, functions are absolutely essential. Data analysts frequently write functions to clean datasets, calculate statistics, or generate reports. For instance, a function might standardise phone numbers by removing spaces and formatting them consistently, or calculate monthly sales totals from daily transaction data. Rather than copying and pasting the same data cleaning code for each new dataset, analysts create functions they can reuse across different projects, saving enormous amounts of time and reducing errors.
Web developers use functions extensively to handle user interactions and process data. A function might validate whether an email address is properly formatted before allowing a user to register for an account, or calculate shipping costs based on a customer's location and order weight. E-commerce websites rely on functions to process payments, update inventory levels, and send confirmation emails. These functions ensure that complex business logic is handled consistently every time a customer makes a purchase.
In financial services, functions are crucial for risk calculations, portfolio analysis, and regulatory reporting. A quantitative analyst might write functions to calculate Value at Risk for investment portfolios, or to determine loan approval based on credit scores and income ratios. These functions often incorporate complex mathematical models but present simple interfaces that other team members can use without understanding the underlying complexity.
Automation specialists use functions to streamline repetitive tasks across various industries. For example, a function might automatically generate monthly reports by pulling data from multiple systems, formatting it consistently, and emailing it to stakeholders. In marketing roles, functions could analyse customer behaviour data to segment audiences or calculate campaign effectiveness metrics. The beauty of functions is that once written and tested, they can run reliably without manual intervention.
Functions also promote collaboration in professional environments. When working on large projects with multiple developers, functions allow team members to work on different parts of the system independently. One developer might create functions for user authentication whilst another writes functions for data processing. Because functions have clear inputs and outputs, team members can integrate their work seamlessly, making professional software development both efficient and manageable.
Syntax
Some examples of the syntax for functions:
# 1. E-COMMERCE: Calculate shipping costs
def calculate_shipping(weight, distance, is_express=False):
"""Calculate shipping cost based on weight, distance and delivery type"""
base_cost = weight * 0.5 # 50p per kg
distance_cost = distance * 0.02 # 2p per mile
total = base_cost + distance_cost
if is_express:
total *= 1.5 # 50% surcharge for express delivery
return round(total, 2)
# 2. FINANCE: Calculate loan monthly payments
def calculate_monthly_payment(principal, annual_rate, years):
"""Calculate monthly mortgage/loan payment using standard formula"""
monthly_rate = annual_rate / 12 / 100
num_payments = years * 12
if monthly_rate == 0: # Handle 0% interest
return principal / num_payments
payment = principal * (monthly_rate * (1 + monthly_rate)**num_payments) / \
((1 + monthly_rate)**num_payments - 1)
return round(payment, 2)
# 3. DATA ANALYSIS: Clean and validate email addresses
def clean_email(email):
"""Standardise email format and validate basic structure"""
if not email or '@' not in email:
return None
email = email.strip().lower()
# Basic validation - contains @ and domain
if email.count('@') == 1 and '.' in email.split('@')[1]:
return email
return None
# 4. MARKETING: Calculate customer lifetime value
def calculate_clv(avg_purchase, purchase_frequency, customer_lifespan):
"""Calculate Customer Lifetime Value for marketing analysis"""
return round(avg_purchase * purchase_frequency * customer_lifespan, 2)
# 5. HR/PAYROLL: Calculate employee gross pay
def calculate_gross_pay(hourly_rate, hours_worked, overtime_multiplier=1.5):
"""Calculate gross pay including overtime (over 40 hours)"""
if hours_worked <= 40:
return hours_worked * hourly_rate
else:
regular_pay = 40 * hourly_rate
overtime_hours = hours_worked - 40
overtime_pay = overtime_hours * hourly_rate * overtime_multiplier
return round(regular_pay + overtime_pay, 2)
# 6. INVENTORY MANAGEMENT: Check stock levels and reorder
def check_reorder_needed(current_stock, minimum_threshold, lead_time_days, daily_usage):
"""Determine if inventory reorder is needed based on usage patterns"""
reorder_point = (daily_usage * lead_time_days) + minimum_threshold
return current_stock <= reorder_point
# 7. HEALTHCARE: Calculate BMI and category
def calculate_bmi_category(weight_kg, height_m):
"""Calculate BMI and return category for health assessments"""
bmi = weight_kg / (height_m ** 2)
bmi = round(bmi, 1)
if bmi < 18.5:
category = "Underweight"
elif bmi < 25:
category = "Normal weight"
elif bmi < 30:
category = "Overweight"
else:
category = "Obese"
return {"bmi": bmi, "category": category}
# 8. RETAIL: Apply discount based on customer tier
def apply_customer_discount(order_total, customer_tier):
"""Apply discount based on customer loyalty tier"""
discounts = {
"bronze": 0.05, # 5%
"silver": 0.10, # 10%
"gold": 0.15, # 15%
"platinum": 0.20 # 20%
}
discount_rate = discounts.get(customer_tier.lower(), 0)
discount_amount = order_total * discount_rate
final_total = order_total - discount_amount
return {
"original_total": order_total,
"discount_amount": round(discount_amount, 2),
"final_total": round(final_total, 2)
}
# 9. PROJECT MANAGEMENT: Calculate project completion percentage
def calculate_project_progress(completed_tasks, total_tasks, completed_hours, estimated_hours):
"""Calculate project completion based on tasks and time"""
task_completion = (completed_tasks / total_tasks) * 100
time_completion = (completed_hours / estimated_hours) * 100
# Weighted average - tasks 60%, time 40%
overall_progress = (task_completion * 0.6) + (time_completion * 0.4)
return round(overall_progress, 1)
# 10. QUALITY ASSURANCE: Validate product specifications
def validate_product_specs(length, width, height, weight, tolerance=0.02):
"""Check if product dimensions are within acceptable tolerances"""
target_specs = {"length": 10.0, "width": 5.0, "height": 2.0, "weight": 0.5}
results = {}
measurements = {"length": length, "width": width, "height": height, "weight": weight}
for spec, measured in measurements.items():
target = target_specs[spec]
deviation = abs(measured - target) / target
results[spec] = {
"measured": measured,
"target": target,
"within_tolerance": deviation <= tolerance,
"deviation_percent": round(deviation * 100, 2)
}
results["overall_pass"] = all(spec["within_tolerance"] for spec in results.values())
return results
# EXAMPLE USAGE OF THE FUNCTIONS:
if __name__ == "__main__": #This line checks whether the Python file is being run directly (as the main program) rather than being imported as a module, so the code inside only executes when you run the file itself.
print("=== REAL JOB FUNCTION EXAMPLES ===\n")
# 1. Shipping calculation
shipping = calculate_shipping(2.5, 150, True)
print(f"Express shipping for 2.5kg over 150 miles: £{shipping}")
# 2. Loan payment
payment = calculate_monthly_payment(250000, 3.5, 25)
print(f"Monthly payment for £250k mortgage at 3.5% over 25 years: £{payment}")
# 3. Email cleaning
clean = clean_email(" JOHN.DOE@COMPANY.COM ")
print(f"Cleaned email: {clean}")
# 4. Customer lifetime value
clv = calculate_clv(50, 4, 3)
print(f"Customer lifetime value: £{clv}")
# 5. Payroll calculation
pay = calculate_gross_pay(15.50, 45)
print(f"Gross pay for 45 hours at £15.50/hour: £{pay}")
# 6. Inventory check
reorder = check_reorder_needed(50, 20, 7, 8)
print(f"Reorder needed: {reorder}")
# 7. BMI calculation
health = calculate_bmi_category(70, 1.75)
print(f"BMI result: {health['bmi']} - {health['category']}")
# 8. Customer discount
discount = apply_customer_discount(100, "gold")
print(f"Gold customer discount: £{discount['discount_amount']} off, final: £{discount['final_total']}")
# 9. Project progress
progress = calculate_project_progress(8, 10, 40, 50)
print(f"Project completion: {progress}%")
# 10. Quality check
quality = validate_product_specs(10.1, 4.9, 2.05, 0.48)
print(f"Quality check passed: {quality['overall_pass']}")