Functions

4. Functions#

Functions let you name a reusable block of code and call it whenever you need that behavior.

  • 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 itself

Video

This short overview introduces Python functions and the basic idea of defining reusable code with def.

Learning Goals

By the end of this chapter, you will be able to:

  1. Define and call custom functions with def

  2. Use parameters, arguments, defaults, *args, and **kwargs

  3. Use return statements to send results back to the caller

  4. Explain local scope, function composition, docstrings, and basic lambda expressions

  5. 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

*args

Syntax that collects extra positional arguments into a tuple

**kwargs

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

Chapter Overview Slides