5. Functions

These notes are provided to demonstrate how to get started with functions in Python. When we write code in almost any programming language, we break up reusable blocks of code into functions.

  • Functions allow us to create an abstraction of the problem we are trying to solve, in a single unit.

  • In any programming language, we will have self- contained blocks of code which we may need to call repeatedly. It would be very wasteful to insert the same code multiple times.

  • I can put the complicated stuff in a function and treat it like a black box, defining the parameters the function needs to run, and the return values.

  • I can reuse the code if it's needed from multiple places in the program.

  • Breaking my code into functions allows me to plan in a modular manner, and in a team, perhaps allocate functions to different teams or groups.

  • When I'm testing and automating testing, I can do so in a per function basis.

  • Variable scope takes accounts of whether a variable is globally visible or only visible to a function. This allows me to encapsulate data and code in a function. We'll see this in more detail whom we examine object-oriented code and namespaces.

There is a deeper philosophy behind the concept of functional programming, feel free to do some background reading. As a formal definition, functional programming does computation by combining functions that take arguments and return value(s) as a result, without modifying the input arguments or the program state.

Before you begin. create a directory to keep example files in and you are ready to code.

This could be on your OneDrive, in these examples, I am using OneDrive\Python\Exercises_05