Walkthrough: Square & Cube
例题: 平方和立方
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 definitionsquare— the function's name (same rules as variable names)(n)— one parameter:— separates header from bodyreturn 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)
sum_of_powers(2)evaluates2 + square(2) + cube(2)square(2)→ returns4cube(2)→ callssquare(2)→ returns 4, then* 2→ 8- sum:
2 + 4 + 8→ 14
Next
Try modifying the example, then move to Clamp — your first function with three parameters.