Index Ai Academy
Phase 0 · ToolsPython core

Functions

About 25 minLooking ahead: some prerequisites aren't done yet

Why this matters

AI code is built from small functions. One builds the prompt, one calls the model, one scores the reply. When you ask an AI assistant to change your code, functions are the pieces you talk about: "make build_prompt include the brand voice". They also make code testable. The exercise checks in this academy work by calling your functions with known inputs and comparing what comes back.

  • Define a function with parameters and call it with arguments
  • Hand a value back with return, and know when print is the wrong choice
  • Give parameters default values and call functions with keyword arguments
  • Explain why a variable created inside a function doesn't exist outside it

Packaging steps under a name

So far your code has run once, top to bottom. Say you need the click-through rate for five campaigns. You could copy the formula five times. But every copy is a place for a typo, and changing the formula means changing it five times.

Think of a coffee machine. You don't explain how to make coffee each time. You press one button, and it runs the same steps. A function is that button: it packages the steps under a name, so you can run them whenever you need them:

def click_through_rate(clicks, impressions):
    return clicks / impressions

print(click_through_rate(5470, 182340))
print(click_through_rate(2050, 410200))

The pieces:

  • def starts a function definition, followed by the function's name.
  • The names in parentheses, clicks and impressions, are parameters: placeholders for the values the function will be given.
  • The colon and the indented block form the body, the steps that run each time.
  • return hands a value back to whoever called the function.

Defining a function doesn't run it. It runs when you call it: the name, followed by parentheses holding the values to use. Those values are the arguments. In click_through_rate(5470, 182340), 5470 goes into clicks and 182340 into impressions, matched by position.