4. Functions#
Functions let you name a reusable block of code and call it whenever you need that behavior. This chapter covers how to define functions, pass information with parameters, return results, design readable functions, and understand recursion as a function that calls itself.
Functions reduce repetition by giving a name to a reusable process.
Parameters let a function work with different inputs.
Return values let a function produce a result for later code to use.
Scope controls where names are available.
Recursion solves a problem by reducing it to smaller versions of the same problem.
Video
This short overview introduces Python functions and the basic idea of defining reusable code with def.
Learning Goals
Define and call custom functions with
defUse parameters, arguments, defaults,
*args, and**kwargsUse
returnstatements to send results back to the callerExplain local scope, function composition, docstrings, and basic lambda expressions
Trace recursive function calls using base cases and recursive cases
Chapter Flow
Glossary
Term |
Meaning |
|---|---|
Function |
A named, reusable block of code |
Parameter |
A variable name listed in a function definition |
Argument |
A value passed into a function call |
Return value |
The result a function sends back to the caller |
Scope |
The region of a program where a name can be used |
Docstring |
A string that documents what a function does |
Lambda |
A small anonymous function written as a single expression |
|
Syntax that collects extra positional arguments into a tuple |
|
Syntax that collects extra keyword arguments into a dictionary |
Recursion |
A pattern where a function calls itself |
Base case |
The stopping condition in a recursive function |
Recursive case |
The part of a recursive function that calls itself on a smaller problem |