Python Functions & Modular Code
Master reusable modular programming: defining functions with def, function invocation, parameters vs arguments, return vs print(), default parameters, integrating conditions & loops, and building practical data analysis pipelines.
1. Why Do We Need Functions?
Imagine calculating tax, shipping fees, or conversion rates in 50 different places across your codebase. If the tax rate changes, you would have to find and update all 50 places manually.
# Price 1 tax1 = 500 * 0.18 # Price 2 tax2 = 1200 * 0.18 # Price 3 tax3 = 3500 * 0.18 # If rate changes to 0.12, fix every line!
def calc_tax(price):
return price * 0.18
tax1 = calc_tax(500)
tax2 = calc_tax(1200)
tax3 = calc_tax(3500)
# Rate change? Update in ONE place only!2. Defining & Calling a Function
In Python, functions are defined using the def keyword, followed by the function name, parentheses (), and a colon ::
def greet():
print("Hello!")
# 2. CALLING the function (executes the code body)
greet()
print("Hello!") and returns to callerdef greet(): print("Hello") and run the program without calling greet(), nothing will print.3. 🔥 Live Lab: Create Your First Function
Define a function named greet() and then call it:
def greet():, indent 4 spaces, print "Hello from Pathubs", and call greet().4. Parameters vs Arguments
Functions become truly powerful when they accept inputs. Beginners often confuse parameters with arguments:
The variable named in the function definition.
print("Hello", name)
The real data value passed when calling the function.
greet("Priya")
5. 🔥 Live Lab: Functions with Multiple Inputs
Create a function that accepts two parameters: price and quantity:
def calculate_total(price, quantity): to print price * quantity. Test with calculate_total(500, 3) and calculate_total(1200, 2).6. Return vs Print: The Most Critical Concept
This is one of the most important conceptual milestones in Python:
Displays characters on screen. The value cannot be stored or reused!
def add(a, b):
print(a + b)
res = add(10, 20)
print(res) # None!Sends the calculated value back to the caller for storage and reuse!
def add(a, b):
return a + b
res = add(10, 20)
print(res) # 30! Can be used in mathreturn statement automatically returns None.7. 🔥 Live Lab: Returning & Reusing Calculated Values
Write a function that returns the total so your program can apply further math:
- Define
calculate_total(price, quantity)that returnsprice * quantity - Call it with
price=1000, quantity=2and store in variablesubtotal - Print
"Subtotal:", subtotal - Compute
tax = subtotal * 0.1and print"Tax:", tax
8. Practical Comparison: When to Use Print vs Return
| Feature | print() | return |
|---|---|---|
| Primary Purpose | Display information for the human user | Deliver data back to the program |
| Can Store in Variable? | No (stores None) | Yes (stores the actual result) |
| In Data Analytics Pipelines | Quick debugging and progress logs | Transforming rows, cleaning columns, calculating KPIs |
| Function Termination | Does NOT terminate the function | Immediately exits the function |
9. Default Parameters
You can specify default values for parameters. If the caller does not supply an argument, Python falls back to the default:
print(message, name)
greet("Amit") # Uses default: "Hello Amit"
greet("Priya", "Good morning") # Overrides default: "Good morning Priya"
10. Functions + Conditions & Loops
Functions allow you to encapsulate decision-making logic and repeat it cleanly across entire datasets:
if sales >= 50000:
return "Target achieved"
return "Target not achieved"
11. Practical Data Analytics: Processing Lists with Functions
Apply your business rule function to a list of monthly sales figures:
12. 🔥 Live Function Challenge: Discount Calculator
Build a pricing utility function from scratch:
13. Common Beginner Mistakes Checklist
| Mistake | Incorrect Code | Correct Code | Why It Fails |
|---|---|---|---|
Forgetting def | calculate(): | def calculate(): | def is the required keyword that introduces a function. |
| Defining but never calling | def greet(): print("Hi") | greet() | Function definitions do not execute automatically. |
Using print() instead of return | def add(a,b): print(a+b) | def add(a,b): return a+b | Caller cannot store or reuse the computed value (receives None). |
| Wrong argument count | calculate_total(500) | calculate_total(500, 3) | Missing required positional arguments throws a TypeError. |
14. 🔥 Final Live Project: Sales Analyzer Pipeline
Build a modular sales performance pipeline with two reusable functions:
- Function 1:
calc_revenue(unit_price, units_sold)→ returnsunit_price * units_sold - Function 2:
check_performance(revenue, target=100000)→ returns"Excellent"ifrevenue >= target, otherwise returns"Needs improvement" - Test your pipeline with
unit_price=2500, units_sold=50(revenue = 125,000) and print results!
15. Core Concept Quick Reference
16. Comprehensive Knowledge Assessment
Test your mastery of Python functions, return mechanics, parameter scoping, and default arguments:
Python Functions Mastery Quiz
Test your conceptual understanding of Python function definitions, parameter vs argument distinction, return mechanics, and default values.
1. What happens when a function without an explicit return statement finishes executing in Python?