Phase 02 · Python FoundationsLesson 5 of 8
Functions, Arguments & Lambdas
Package logic into reusable functions and pass data in flexibly.
The problem
Every program you write eventually repeats itself: you validate an email in three places, you format a price in five. Functions let you write that logic once, give it a name, and reuse it anywhere. They are the single most important tool for keeping code readable, and every AI framework you'll use later (ADK, AutoGen, LangChain) is built on top of them.
The concept
What is a function?#
A function is a named block of code that takes some inputs (parameters), does some work, and optionally gives back an output (the return value).
def greet(name):
return f"Hello, {name}!"
message = greet("Ada")
print(message) # Hello, Ada!
defstarts the definition, followed by the function's name and its parameters in brackets.- The indented block is the body: the code that runs every time the function is called.
returnsends a value back to whoever called the function.
What a function does
- Inputsparameters, e.g.
name - Bodythe indented code that does the work
- Outputthe return value, e.g.
"Hello, Ada!"
Parameters vs arguments#
These two words get mixed up constantly, so it's worth being precise:
| Term | What it means | In greet("Ada") |
|---|---|---|
| Parameter | The placeholder name in the definition | name |
| Argument | The actual value you pass when calling | "Ada" |
Default arguments#
Give a parameter a default value and it becomes optional:
def greet(name="there", greeting="Hello"):
return f"{greeting}, {name}!"
greet() # 'Hello, there!'
greet("Ravi") # 'Hello, Ravi!'
greet("Ravi", "Welcome") # 'Welcome, Ravi!'
greet(greeting="Hi") # 'Hi, there!' ← keyword argument
Calling with greeting="Hi" is a keyword argument: you name the parameter, so order no longer matters. Keyword arguments make calls much easier to read when a function has several options.
Flexible inputs: *args and **kwargs#
Sometimes you don't know how many arguments will be passed.
def total(*prices):
return sum(prices)
total(10, 20, 30) # 60 → prices is the tuple (10, 20, 30)
def build_profile(**details):
return details
build_profile(name="Ada", role="Engineer")
# {'name': 'Ada', 'role': 'Engineer'}
*argscollects extra positional arguments into a tuple.**kwargscollects extra keyword arguments into a dictionary.
*args
- Collects extra positional arguments
- Stored as a tuple
total(10, 20, 30)gives(10, 20, 30)
**kwargs
- Collects extra keyword arguments
- Stored as a dictionary
build_profile(name="Ada", role="Engineer")gives{'name': 'Ada', 'role': 'Engineer'}
The names args and kwargs are only a convention; the * and ** are what matter.
Return values and None#
A function can return any value: a number, a list, a dictionary, even another function. If it reaches the end without a return statement, Python returns None automatically.
def log(message):
print(f"[LOG] {message}")
result = log("Started")
print(result) # None
Scope: where variables live#
Variables created inside a function are local: they exist only while the function runs and can't be seen outside it. This is a feature, not a limitation. It means two functions can both use a variable called total without interfering with each other.
Lambdas: tiny one-line functions#
A lambda is a small anonymous function written in a single expression. It's handy when you need a quick function to pass into another function:
students = [("Ada", 91), ("Ravi", 78), ("Meera", 85)]
# Sort by score (the second item), highest first
ranked = sorted(students, key=lambda s: s[1], reverse=True)
# [('Ada', 91), ('Meera', 85), ('Ravi', 78)]
squares = list(map(lambda x: x * x, [1, 2, 3])) # [1, 4, 9]
If a lambda grows beyond one simple expression, turn it into a regular def with a descriptive name. Readability wins.
Why this matters for AI work#
When you build agents later in this track, the "tools" an agent can use are just Python functions with clear names, parameters and docstrings. The model reads the function's signature to decide when and how to call it. Writing clean, well-named functions now is directly practice for building reliable agents later.
Try it
Your task · about 10 minutes
Write average(*nums) that returns the mean of any number of arguments, and returns None when called with none.
Recap & next
Key takeaways
- Define with
def name(params):and send a result back withreturn. - A function without
returnreturnsNone. - Default arguments make parameters optional:
def greet(name="there"). *argscollects extra positional arguments into a tuple;**kwargscollects keyword arguments into a dict.lambda x: x * 2creates a small anonymous function, handy withmap,filterandsorted.
Quick check
2 questions · instant feedback
Go deeper
Finished this lesson?
Mark it complete to track your progress and keep your streak going.




