Lesson 2 of 5 · 7 min · The language
Functions, arguments, *args and **kwargs
What you will learn
- Define and call functions, and return values
- Positional, keyword and default arguments
- What
*argsand**kwargscollect - Local and global scope
- Small anonymous functions with
lambda
In simple words
A function is a named recipe. You give it ingredients (arguments), it follows the steps and hands back a dish (the return value). You write the recipe once and use it again and again. Python lets you pass ingredients by position, by name, or as a whole bag of extras, which is what *args and **kwargs are.
Words to know
- Function: a named block of code you can run many times.
- Argument: a value you pass to a function when you call it.
- Parameter: the name in the function definition that receives an argument.
- Return value: the result a function gives back with
return.
Defining and calling
def total_with_gst(price, rate=18):
"""Return the price including GST."""
return price + price * rate / 100
print(total_with_gst(1000)) # 1180.0
print(total_with_gst(1000, 5)) # 1050.0
print(total_with_gst(rate=12, price=1000)) # 1120.0
defstarts a function; the indented block is its body.returnends the function and sends a value back. A function with noreturngives backNone.- The text in triple quotes is a docstring;
help(total_with_gst)shows it. - Arguments can be positional (by order) or keyword (by name). Keyword arguments can come in any order.
rate=18is a default: used when the caller leaves it out. Defaults must come after non-default parameters, and must not be mutable objects (lesson 1).
*args and **kwargs
Sometimes you do not know how many arguments will come.
def add_all(*numbers):
return sum(numbers)
print(add_all(1, 2, 3, 4)) # 10
*numbers collects extra positional arguments into a tuple. **options collects extra keyword arguments into a dict:
def make_report(title, **options):
print(title, options)
make_report("Sales", year=2026, region="South")
# Sales {'year': 2026, 'region': 'South'}
The same stars work when calling, to unpack a list or dict into arguments:
values = [1, 2, 3]
print(add_all(*values)) # 10
config = {"price": 1000, "rate": 5}
print(total_with_gst(**config)) # 1050.0
The order in a definition is: normal parameters, then *args, then keyword-only parameters, then **kwargs. A bare * forces the parameters after it to be passed by keyword, and a / makes the ones before it positional-only:
def connect(host, /, port, *, timeout=10):
...
Scope
A name created inside a function is local: it exists only while the function runs. Reading a global name from inside is fine; assigning to one makes a new local name unless you declare global, which you should rarely need.
rate = 18
def show():
print(rate) # reads the global
def broken():
rate = rate + 1 # UnboundLocalError: the assignment makes rate local
Pass values in as parameters and return results instead of changing globals. Python looks names up in this order: local, enclosing function, global, built-in (the LEGB rule).
Functions are values
A function can be stored in a variable, passed to another function, or returned:
def square(x):
return x * x
nums = [3, 1, 2]
print(sorted(nums, key=lambda n: -n)) # [3, 2, 1]
print(list(map(square, nums))) # [9, 1, 4]
A lambda is a one-expression anonymous function: lambda n: -n. Use it for short throwaway keys; use def for anything longer. In data work you will meet it often in pandas (df.apply(lambda row: ...)).
Return several values
A function returns one object, but it can be a tuple, and you can unpack it:
def min_max(values):
return min(values), max(values)
low, high = min_max([4, 9, 2])
print(low, high) # 2 9
Common mistakes
- Forgetting
returnand gettingNone. - A mutable default such as
items=[]. - Printing instead of returning, which makes the function impossible to reuse.
- Changing a global from inside a function without meaning to.
Try it yourself
- Write
discount(price, percent=10)and call it three ways: positional, keyword and mixed. - Write
average(*numbers)that returns the mean, and guard against being called with no numbers. - Write a function that returns the count, sum and average as a tuple, and unpack it.
- Sort a list of dicts by a key using
sorted(..., key=lambda ...).
Check yourself
What do *args and **kwargs hold inside the function?
*args is a tuple of the extra positional arguments, and **kwargs is a dict of the extra keyword arguments.
What does a function return if it has no return statement?
None.
Why does x = x + 1 inside a function raise UnboundLocalError when x is global?
Assigning to a name inside a function makes it local for the whole function, so reading it before the assignment fails. Pass it as an argument or declare it global.
What is the difference between a parameter and an argument?
A parameter is the variable named in the function definition. An argument is the actual value passed when the function is called.
Interview questions
What is a keyword-only argument and why use one?
A parameter placed after * (or after *args) that must be passed by name, such as timeout=5. It makes calls readable and prevents mistakes with long argument lists.
What does the LEGB rule mean?
The order Python searches for a name: Local, Enclosing function, Global, Built-in.
Explain a closure in one example.
A closure is an inner function that remembers variables from the function that created it, for example def make_adder(n): return lambda x: x + n; make_adder(5)(3) is 8 because the lambda keeps n.
Summary
defdefines a function;returnhands back a value (otherwiseNone).- Use defaults, keyword arguments,
*argsand**kwargsfor flexible calls. - Names inside a function are local; pass data in and return results out.
lambdais for short one-expression functions, common as akey.
Going deeper
- More on defining functions: defaults, keyword arguments, unpacking.
- Function definitions: the full syntax including
/and*. - Scopes and namespaces: local, nonlocal and global.
See how much of this you can explain
A free mock interview asks you new questions on Python essentials for analysts for Data Analyst and scores every answer, with what to fix.