Back to website
Mayank Aggarwal Learning Center

Phase 02 · Python FoundationsLesson 5 of 8

Functions, Arguments & Lambdas

Package logic into reusable functions and pass data in flexibly.

  • 12:03 video
  • 4 min read
  • Beginner
01

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.

02

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).

Python
def greet(name):
    return f"Hello, {name}!"

message = greet("Ada")
print(message)  # Hello, Ada!
  • def starts 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.
  • return sends a value back to whoever called the function.

What a function does

  1. Inputsparameters, e.g. name
  2. Bodythe indented code that does the work
  3. Outputthe return value, e.g. "Hello, Ada!"

Parameters vs arguments#

These two words get mixed up constantly, so it's worth being precise:

TermWhat it meansIn greet("Ada")
ParameterThe placeholder name in the definitionname
ArgumentThe actual value you pass when calling"Ada"

Default arguments#

Give a parameter a default value and it becomes optional:

Python
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.

Python
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'}
  • *args collects extra positional arguments into a tuple.
  • **kwargs collects 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.

Python
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:

Python
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.

03

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.

04

Recap & next

Key takeaways

  1. Define with def name(params): and send a result back with return.
  2. A function without return returns None.
  3. Default arguments make parameters optional: def greet(name="there").
  4. *args collects extra positional arguments into a tuple; **kwargs collects keyword arguments into a dict.
  5. lambda x: x * 2 creates a small anonymous function, handy with map, filter and sorted.

Quick check

2 questions · instant feedback

1*args collects extra positional arguments into a…
2What does a function return if it has no return statement?

Finished this lesson?

Mark it complete to track your progress and keep your streak going.

Next