Python Functions
Python · Functions & OOP
Theory
A function is a named, reusable block of code. You define it once with the def keyword, give it parameters (the inputs it expects), and call it as many times as you like with different arguments (the actual values). Inside the body, return sends a value back to the caller and ends the function immediately; a function with no return gives back None.
For example, total_sales(sales) receives a list, adds it up with sum() and returns the total, so total_sales([100, 250, 300]) evaluates to 650. Parameters can have default values (def greet(name, msg='Hi')), which makes those arguments optional, and callers may pass arguments by position or by name (greet(msg='Hello', name='Asha')).
Why we use it
Without functions you copy and paste the same logic everywhere, and every bug has to be fixed in many places. A function gives that logic one name and one home, making code shorter, easier to test and easier to read.
When to use it
Write a function as soon as you repeat a piece of logic twice, or when a block does one clear job (clean a column, compute tax). For a tiny one-off expression passed to sorted() or map(), a lambda is often enough.
How it works
- Caller runs total_sales([100, 250, 300])
- Python binds the argument to the parameter sales
- Execute the body line by line
- Is a return statement reached? Yes: Send the value back and exit. No: Return None at the end.
- Caller receives 650 and continues
Syntax
def function_name(params):
return valueExample
def total_sales(sales):
return sum(sales)Key points
- Default parameter values make arguments optional
- return exits the function immediately with a value
- No return statement means the function returns None
- Parameters are the names in def; arguments are the values you pass
- Never use a mutable default like def f(x=[]) - use None and create the list inside