Course Content
Python Essentials for AI Engineer
6 sections · 48 lessons
What is a function in Python? Why do we use it?
What you need to know
Anatomy of a function
1def clean_text(text: str, max_chars: int = 2000) -> str:2 """Normalise whitespace and cut the text to fit a prompt."""3 text = " ".join(text.split()) # collapse spaces, tabs, newlines4 return text[:max_chars]56print(clean_text(" Refund not\n received \t ")) # Refund not received7print(clean_text.__doc__) # Normalise whitespace and cut the text to fit a prompt.defstarts the definition;clean_textis its name.textandmax_charsare parameters;max_charshas a default.- The string on the first line of the body is the docstring — documentation that tools and
help()can read. returnsends the result back to the caller. A function with noreturnreturnsNone.: strand-> strare 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
- No repetition (DRY — Don't Repeat Yourself). Code that exists once needs fixing once.
- Naming.
clean_text(msg)says what happens; ten inline lines do not. - Testing. A function with inputs and an output can be unit-tested with
assert clean_text(" a ") == "a". - 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:
1steps = [str.strip, str.lower, clean_text]2text = " HELLO World "3for step in steps:4 text = step(text)5print(text) # hello worldThis 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.