Functions, args and lambdas

Every AI helper (generate_text(), execute_tool(), calculate_similarity()) is a Python function. Functions let you write code once and reuse it everywhere. Let us build some.

Function call anatomy

How arguments flow into a function and return values flow out

functions.py
python
# Basic function with default parameter
def create_message(content, role="user"):
    return {"role": role, "content": content}

print(create_message("What are top products?"))
print(create_message("You are helpful.", role="system"))

# Multiple return values
def analyze_text(text):
    words = text.split()
    return len(words), len(text)

word_count, char_count = analyze_text("Hello world from Python")
print(f"Words: {word_count}, Characters: {char_count}")

Functions use def, can have default parameters, and return values. Multiple return values are packed as a tuple and unpacked with commas.

args collects extra positional arguments as a tuple. *kwargs collects extra keyword arguments as a dictionary. Libraries use them to accept flexible inputs. You will see them in SDK wrappers that pass options through to the underlying API.

functions.py
python
# *args and **kwargs in action
def log_event(*args, **kwargs):
    """Accepts any number of positional and keyword arguments."""
    print(f"Args: {args}")
    print(f"Kwargs: {kwargs}")

log_event("query", "SQL", user="param", score=5)
# Args: ('query', 'SQL')
# Kwargs: {'user': 'param', 'score': 5}

*args collects extra positional arguments as a tuple. **kwargs collects extra keyword arguments as a dictionary. Libraries use them to accept flexible inputs.

Lambda functions are small, one-line functions without a name. They are used when you need a quick function for a single operation, most commonly as the key= parameter in sort() to tell Python what value to compare.

functions.py
python
# Lambda functions (small inline functions)
results = [("Quinoa Bowl", 0.88), ("Mac & Cheese", 0.53), ("Tofu Tacos", 0.71)]

# Sort by score (the second element in each tuple)
results.sort(key=lambda x: x[1], reverse=True)
print("Ranked results:")
for dish, score in results:
    print(f"  [{score:.2f}] {dish}")

# Useful built-ins for numbers
token_counts = [150, 320, 85, 210, 475]
print(f"Total: {sum(token_counts)}, Min: {min(token_counts)}, Max: {max(token_counts)}")

lambda x: x[1] creates a function that returns the second element. sort() uses this to rank by score. sum(), min(), max() are built-ins you will use for token counting.

Matching exercise: Match function concepts

Loading practiceโ€ฆ

Fill in the blanks: Complete the sorting Lambda

Loading practiceโ€ฆ

Flashcards: Flashcards

Loading practiceโ€ฆ

Validation checklist: Functions checklist

Loading practiceโ€ฆ