Loading lesson…
A function is a reusable chunk of code with a name. You'll write three, add type hints, and let AI suggest better names and docstrings.
A function packages logic so you can call it by name anywhere. Name it clearly and your code reads like a story. Name it 'do_stuff' and your future self will curse your past self.
def greet(name: str, enthusiasm: int = 1) -> str: """Return a friendly greeting. Args: name: the person to greet enthusiasm: number of exclamation marks (default 1) """ bangs = "!" * enthusiasm return f"Hello, {name}{bangs}" print(greet("Maya")) print(greet("Maya", enthusiasm=5))Type hints (: str, -> str) are optional but massively improve both human and AI understanding.def add_broken(a, b): print(a + b) # shows the answer — but returns None def add_good(a, b): return a + b # gives the answer back to the caller result = add_broken(2, 3) # prints 5, but result is None total = add_good(2, 3) # total is 5 — usable print(result * 2) # TypeError: NoneType print(total * 2) # 10If a function needs to be usable in another function, it must return, not print.| Loose function | Tight function |
|---|---|
| def do(x) | def fetch_user(user_id: int) -> dict |
| No docstring | Docstring with Args and Returns |
| Prints results | Returns results |
| Hard to test | Easy to test |
Big idea: a function is a small contract. Its name says what it does, its signature says how to use it, its docstring says why. AI pair-programming gets dramatically better when you tighten those three things up first.
8 questions · take it digitally for instant feedback at tendril.neural-forge.io/learn/quiz/end-prog-python-functions-builders
What is the main idea of "Python Functions — Writing Your Own Tools"?
Which concept is most central to "Python Functions — Writing Your Own Tools"?
Which use of AI fits this topic best?
What should a careful learner remember about "Docstrings make AI smarter"?
You want to use AI after this lesson. What is the safest next step?
How should AI output about functions be treated?
Name one way to verify an AI answer about functions.
Which action would help you apply "Python Functions — Writing Your Own Tools" responsibly?