W WolfCode · CSC 141

Walkthrough: Square & Cube

例题: 平方和立方

≈ 8 min · python-functions · Open in WolfCode

The minimum-viable function example — three fruitful functions that compose. def + return + a function calling another.

The three functions

Python · runnable

Anatomy of def square(n):

  • def — keyword that introduces a function definition
  • square — the function's name (same rules as variable names)
  • (n) — one parameter
  • : — separates header from body
  • return n * n — sends the result back to the caller

The fruitful-vs-void trap

A function that prints isn't the same as one that returns

Composition in action — trace sum_of_powers(2)

  1. sum_of_powers(2) evaluates 2 + square(2) + cube(2)
  2. square(2) → returns 4
  3. cube(2) → calls square(2) → returns 4, then * 2 → 8
  4. sum: 2 + 4 + 814

Next

Try modifying the example, then move to Clamp — your first function with three parameters.