6.1 Defining functions
Learning objectives
By the end of this section you should be able to
- Identify function calls in a program.
- Define a parameterless function that outputs strings.
- Describe benefits of using functions.
Calling a function
Throughout the book, functions have been called to perform tasks. Ex: print prints values, and sqrt calculates the square root. A function is a named, reusable block of code that performs a task when called.
Defining a function
A function is defined using the def keyword. The first line contains def followed by the function name (in snake case), parentheses (with any parameters—discussed later), and a colon. The indented body begins with a documentation string describing the function's task and contains the function statements. A function must be defined before the function is called.
Benefits of functions
A function promotes modularity by putting code statements related to a single task in a separate group. The body of a function can be executed repeatedly with multiple function calls, so a function promotes reusability. Modular, reusable code is easier to modify and is shareable among programmers to avoid reinventing the wheel.
Adapted from Introduction to Python Programming by OpenStax (openstax.org), licensed under CC BY-NC-SA 4.0. Changes were made. License: CC-BY-NC-SA-4.0.