Overview

9 Functions

This chapter presents a practical tour of Python functions, from basic definitions and returns to more advanced patterns you’ll use every day. It explains how indentation defines a function’s body, how return values work (including the implicit None), and why docstrings belong inside functions to describe behavior and parameters, while comments explain internal mechanics. Throughout, examples emphasize writing clear, single-purpose functions and show how to call them and use or ignore their results as needed.

You learn Python’s flexible parameter system in depth: positional and default parameters, keyword (named) arguments for clarity, and variable-length arguments with *args and **kwargs. The chapter shows how to combine these mechanisms safely and readably, and it highlights how argument passing works by object reference. Special attention is given to mutability: mutating a passed-in list or dict affects the caller, while reassignment does not; using a mutable object as a default parameter is a common pitfall that leads to shared state across calls.

The discussion then covers scope and state management—local variables, and when to use global and nonlocal for assignments in enclosing scopes—followed by functions as first-class objects that can be assigned, stored in containers, and selected dynamically. You see how lambdas provide concise, inline functions; how generator functions and yield (plus yield from) let you build efficient, resumable iterators; and how decorators wrap behavior cleanly with the @ syntax. The chapter concludes with a refactoring lab and guidance: prefer small, focused functions, avoid hidden side effects and accidental globals, and favor docstrings for discoverable documentation.

At the beginning of function f(), both the initial variables and the function parameters refer to the same objects.
At the end of function f(), y (list1 inside the function) has been changed internally, whereas n and list2 refer to different objects.

Summary

  • The basic function is defined using the def keyword, a name, parenthesis, and colon followed by a code block with an optional return statement at the end.
  • Arguments may be passed by position or by parameter name.
  • Default values may be provided for function parameters.
  • Functions can collect arguments into tuples, giving you the ability to define functions that take an indefinite number of arguments.
  • Functions can collect arguments into dictionaries, giving you the ability to define functions that take an indefinite number of arguments passed by parameter name.
  • External variables can easily be accessed within a function by using the global or nonlocal keywords.
  • The lambda keyword is used to create anonymous inline functions.
  • Generator objects are created by functions that use yield or yield from instead of return.
  • Functions are first-class objects in Python, which means that they can be assigned to variables, accessed by way of variables, and decorated.

FAQ

How do I define a function in Python, and what does return do?Use def name(params): followed by an indented body. A return statement sends a value back to the caller; if you omit it, the function returns None. You can place a triple-quoted docstring right after the header to document the function, accessible via func.__doc__.
What’s the difference between positional, keyword, and default parameters?Positional arguments are matched by order. Keyword arguments use name=value and can be passed in any order. Defaults are set in the definition (for example, def power(x, y=2): ...) and are used when the caller omits that argument. Parameters with defaults must come after non-default ones.
How do I accept a variable number of arguments?Use *args to collect extra positional arguments into a tuple and **kwargs to collect extra keyword arguments into a dictionary (for example, def f(a, *args, **kwargs): ...). When defining, place *args before **kwargs; when calling, pass positional arguments before keyword arguments.
Can I mix positional and keyword arguments safely?Yes. In calls, pass positional arguments first and then keyword arguments (for example, fn(1, 2, x=3, y=4)). In definitions, a common order is def fn(a, b, c=0, *args, **kwargs): .... Keep it simple to avoid confusion and errors.
What happens when I pass mutable vs. immutable objects to a function?Parameters are references to objects. Mutating a mutable object (like a list or dict) inside a function affects the caller’s object (for example, lst.append(3)). Rebinding the parameter (for example, lst = [1,2]) only changes the local reference and does not affect the caller. Immutable objects (ints, strs, tuples) can’t be mutated; reassignment only changes the local reference.
Why are mutable default arguments dangerous and how do I avoid the pitfall?Default values are evaluated once at function definition time. If you use a mutable default (for example, def add(x, bag=[]): bag.append(x)), that same list is reused across calls. The safe pattern is def add(x, bag=None): then inside do if bag is None: bag = [].
What are local, global, and nonlocal variables?Local variables are created inside a function and are not visible outside. Use global name inside a function to assign to a module-level variable. Use nonlocal name inside a nested function to assign to a variable from the nearest enclosing (non-global) scope. Reading outer names needs no declaration; assigning does.
Can I assign functions to variables or store them in data structures?Yes. Functions are first-class objects. You can do op = abs and call op(-3), or store functions in dicts/lists (for example, ops = {"FtoK": f_to_kelvin, "CtoK": c_to_kelvin} and then ops["FtoK"](32)).
What are lambda expressions and when should I use them?A lambda creates a small anonymous function: lambda x: x * 2. It must be a single expression (return is implicit). Use it for short, throwaway functions (for example, sorted(words, key=lambda w: len(w))). If the logic grows, prefer a named def function.
How do generator functions work, and what’s the difference between yield and yield from?Generators use yield to produce a sequence of values and preserve state between iterations (for example, def count(n): for i in range(n): yield i). They stop when the function ends or hits return. yield from iterable delegates yielding to a sub-iterator, letting you compose generators more cleanly.
What is a decorator and how do I write one?A decorator is a function that takes a function and returns a new function that typically adds behavior. Define it as def deco(f): def wrapper(*a, **k): ...; return f(*a, **k); return wrapper. Apply with @deco above a function definition. Common uses include logging, access control, caching, and registration.

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • The Quick Python Book, Fourth Edition ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • The Quick Python Book, Fourth Edition ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • The Quick Python Book, Fourth Edition ebook for free