Chapter 5Custom Functions and Exceptions
Every modern programming language provides the core capability of grouping statements into a reusable named block of code called a function. Named functions are fundamental building blocks that support the creation of complex programs by assembling smaller groups of related statements. It gives us the tools to encapsulate the details of a specific computation as a reusable named block of code and then to use these blocks to reason at higher levels of abstraction. Functions allow us to organize our code in meaningful ways and to test individual blocks of code independent of the others. The utilization of functions enables us to more easily and reliably assemble logical procedures that solve increasingly complex problems without becoming mired in detail. The benefits of using functions and other related tools in Python will become more evident as we begin to define and use functions to solve problems.
5.1 Defining Custom Functions
A custom Python function is defined using a format outlined in Figure 5.1. Function definitions begin with a line that starts with the def keyword, followed by a function name, parentheses, and ends with a colon. Arguments may be passed into a function when the function is invoked by placing the argument values between the parentheses. These argument values are assigned to variables that appear between the parentheses of a function definition, referred to as the function’s parameters. The top line of a Python ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access