Python Essentials for AI Engineer

Course Content

Python Essentials for AI Engineer

6 sections · 48 lessons

What is a function in Python? Why do we use it?


One definition of clean, used everywhereclean_text() ina shared moduleTraining scriptValidation notebookFastAPI endpointUnit test pins the behaviour
With one function instead of four copies, a fix can no longer reach training and miss serving — the cause of the 91 to 84 percent drop.

What you need to know

Anatomy of a function

Python
def clean_text(text: str, max_chars: int = 2000) -> str:    """Normalise whitespace and cut the text to fit a prompt."""    text = " ".join(text.split())      # collapse spaces, tabs, newlines    return text[:max_chars]print(clean_text("  Refund   not\n received \t "))   # Refund not receivedprint(clean_text.__doc__)    # Normalise whitespace and cut the text to fit a prompt.
  • def starts the definition; clean_text is its name.
  • text and max_chars are parameters; max_chars has a default.
  • The string on the first line of the body is the docstring — documentation that tools and help() can read.
  • return sends the result back to the caller. A function with no return returns None.
  • : str and -> str are optional type hints.

The body does not run when Python reads the def. It runs each time you call the function.

Why we use functions

  1. No repetition (DRY — Don't Repeat Yourself). Code that exists once needs fixing once.
  2. Naming. clean_text(msg) says what happens; ten inline lines do not.
  3. Testing. A function with inputs and an output can be unit-tested with assert clean_text(" a ") == "a".
  4. Composition. Small functions combine into a pipeline, each one replaceable.

Functions are objects

A function is a value like any other. You can store it in a variable, put it in a list, or pass it as an argument:

Python
steps = [str.strip, str.lower, clean_text]text = "  HELLO   World "for step in steps:    text = step(text)print(text)          # hello world

This is what makes sorted(items, key=some_function), decorators and callbacks possible.

A real-life example

A data scientist builds a support-ticket classifier in a notebook. The text-cleaning code is copy-pasted in four cells: training, validation, the demo, and later the FastAPI endpoint. A bug fix (removing phone numbers) gets applied to three copies but not the endpoint. In production the model now sees text that is cleaned differently from what it was trained on — training-serving skew — and accuracy drops from 91% to 84%, with no error anywhere.

The fix is one clean_text() function in a shared module, imported by both the training script and the API. Now there is exactly one definition of "clean", and a unit test pins its behaviour.

Follow-up questions to expect

  • "What does a function return if it has no return?" — None.
  • "What is a first-class function?" — A function that can be treated as a value: assigned, passed as an argument, and returned from another function. All Python functions are first-class.
  • "How small should a function be?" — Small enough to do one job you can name in a few words. If its name needs "and" in it, it probably does two jobs.