Python, from Zero, for AILesson 28 of 89

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

Side effects, and why some functions are easy to test

In this lesson

  • 8 min read
  • 6 reading sections
  • Knowledge check
  • Lesson 8 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

Two kinds of function

Python
def with_tax(amount, rate=0.18):
    return round(amount * (1 + rate), 2)

Given the same arguments, this returns the same answer every time, and calling it changes nothing anywhere else. That is a pure function.

Python
def save_invoice(invoice):
    with open("invoices.csv", "a") as f:
        f.write(invoice.as_row())
    logger.info("saved")

This one has side effects: it touches a file and a log. Call it twice and the world is different than if you called it once.

Both kinds are necessary. A program of only pure functions cannot read input or show output, so it does nothing observable. The point is not to eliminate side effects; it is to know which functions have them.

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) ‘Side effects, and why some functions are easy to test’, in Python, from Zero, for AI. Edited by M. Mun. Addaly. Available at: https://addaly.com/learn/python-for-ai/pure-functions (Accessed: 29 November 2026).