Functions in Python
Write reusable functions to avoid repeating logic across your analysis scripts
Functions package reusable logic under a name you can call anywhere. In data analysis, functions are used to standardise cleaning steps, apply complex business logic to columns, generate formatted reports, and structure your code so a notebook remains readable.
The principle: if you write the same block of code twice, turn it into a function. Functions also make debugging easier — fix it in one place, it is fixed everywhere.
Examples
Key Points
- ✓def function_name(parameters): — always colon and indented body
- ✓return sends a value back — without return, function returns None
- ✓Default arguments make parameters optional: def f(x, y=10)
- ✓Lambda functions are one-line anonymous functions for simple transformations
- ✓.apply(function) applies a function to every value in a Pandas Series or DataFrame row
Practice Question
What does a Python function return if it has no return statement?
Related Topics
Loops — for and whileIterate over data, automate repetitive tasks, and process multiple files with loopsConditionals — if, elif, elseWrite if/elif/else logic to categorise, flag and filter data in PythonPython Best Practices for Data AnalystsWrite clean, readable, professional Python code — habits that matter in team environments