Functions

At the end of the previous chapter, we solved a simple conversion problem, and while the problem was solved, it can be argued that the code we used wasn't exactly perfect; of course, it allowed us to change variable names (for instance, update hotel pricing), but it was still hard to read and error-prone. In addition, some particular elements of the code were repetitive, as we performed the same operations on different values.

This is exactly the opposite of one measure of code quality employed by programmers—Don't Repeat Yourself! (DRY) code—code that has no repeating parts. In other words, operations that we use multiple times should be articulated and defined once. This will allow us to keep the code short, concise, and expressive. It will be easier to maintain, debug, and change when needed. But how can this be achieved? First of all, it is necessary to use functions.

In this chapter, we will understand the concept of functions, review those functions built into Python, and learn how to build our own ones, including, as usual, strict technical requirements, common design patterns, and general conventions. In the process, we will rewrite our solution from Chapter 2First Steps in Coding – Variables and Data Types, and practice on other practical examples.

In particular, we will cover the following topics:

  • Built-in functions
  • Defining the function
  • Refactoring the budget code
  • Anonymous (lambda) functions
  • Recursion
..................Content has been hidden....................

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