Python, from Zero, for AILesson 25 of 89

Module 3 · Functions, modules, and code you can read again in March

Saying what a function expects, and what checks it

In this lesson

  • 8 min read
  • 6 reading sections
  • Knowledge check
  • Lesson 5 of 9 in this chapter

This chapter’s goalSplit a working script into functions and modules with explicit arguments, return values and docstrings, explain from Python’s scoping rules why a variable changed inside a function did or did not change outside it, and run the result from a terminal with named options.

This chapter’s media

The film explains chapter ideas. The audiobook narrates the complete teaching text.

FormatEnglishहिंदी
Chapter filmWatch1:44Not available
Full audiobookNot availableNot available

A little at a time

Explore an idea, try it, then check what stays.

Step 1 of 8Free · no account needed
Lesson steps

The docstring is the first line of the body

Python
def split_bill(total, people, tip_percent=0):
    """Return each person's share, rounded to 2 decimals.

    total: the bill before tip, in rupees
    people: how many are paying; must be at least 1
    tip_percent: 10 means 10 percent

    Raises ValueError if people is less than 1.
    """

A string as the first statement of a function, module or class becomes its documentation. It is not a comment: it is stored on the object, so help(split_bill) prints it, editors show it on hover, and python -m pydoc yourmodule turns a file into readable documentation with no extra tooling.

Write the first line as a sentence saying what the function returns, in the imperative. Then the arguments in terms a caller needs: units, ranges, what “must” means. Then what it raises. Three-quarters of the value is in the units: total in rupees or paise is exactly the sort of thing that gets guessed wrong.

Your place and first choices stay on this browser. Classroom credit is recorded separately.

Stuck on something?Ask Divya, your AI tutor

How to cite: Addaly (2026) ‘Saying what a function expects, and what checks it’, in Python, from Zero, for AI. Edited by M. Mun. Addaly. Available at: https://addaly.com/learn/python-for-ai/docstrings-and-type-hints (Accessed: 29 November 2026).