Functions, the Building Blocks of Code

"To create architecture is to put in order. Put what in order? Functions and objects."
 – Le Corbusier

In the previous chapters, we have seen that everything is an object in Python, and functions are no exception. But, what exactly is a function? A function is a sequence of instructions that perform a task, bundled as a unit. This unit can then be imported and used wherever it's needed. There are many advantages to using functions in your code, as we'll see shortly.

In this chapter, we are going to cover the following:

  • Functions—what they are and why we should use them
  • Scopes and name resolution
  • Function signatures—input parameters and return values
  • Recursive and anonymous functions
  • Importing objects for code reuse

I believe the saying, a picture is worth one thousand words, is particularly true when explaining functions to someone who is new to this concept, so please take a look at the following diagram:

As you can see, a function is a block of instructions, packaged as a whole, like a box. Functions can accept input arguments and produce output values. Both of these are optional, as we'll see in the examples in this chapter.

A function in Python is defined by using the def keyword, after which the name of the function follows, terminated by a pair of parentheses (which may or may not contain input parameters), and a colon (:) signals the end of the function definition line. Immediately afterwards, indented by four spaces, we find the body of the function, which is the set of instructions that the function will execute when called.

Note that the indentation by four spaces is not mandatory, but it is the amount of spaces suggested by PEP 8, and, in practice, it is the most widely used spacing measure.

A function may or may not return an output. If a function wants to return an output, it does so by using the return keyword, followed by the desired output. If you have an eagle eye, you may have noticed the little * after Optional in the output section of the preceding diagram. This is because a function always returns something in Python, even if you don't explicitly use the return clause. If the function has no return statement in its body, or no value is given to the return statement itself, the function returns  None. The reasons behind this design choice are outside the scope of an introductory chapter, so all you need to know is that this behavior will make your life easier. As always, thank you, Python.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset