{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Prerequisites \n",
    "\n",
    "- Types\n",
    "- Collections\n",
    "\n",
    "# Functions\n",
    "\n",
    "Occasionally, there is a particular piece of code that you would like to reuse over-and-over, without having to write the code over-and-over). \n",
    "For this case, Python allows the use of *functions*, these are segments of code to which arguments are passed and some operation is performed on them. \n",
    "You will have already encountered some examples of functions, such as `print()` and `type()`. \n",
    "However, in this section we will introduce how custom functions can be written for your code.\n",
    "A function can be easily recognised in Python as it is some statement followed immediately by a set of brackets (which contain the *arugments*).\n",
    "\n",
    "The general syntax for *defining* a function is Python is as follows, "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2020-04-05T15:05:58.344233Z",
     "start_time": "2020-04-05T15:05:58.334498Z"
    }
   },
   "outputs": [],
   "source": [
    "def kinetic_energy(mass, velocity):\n",
    "    \"\"\"\n",
    "    Determine the kinetic energy of a particle.\n",
    "    \n",
    "    Args:\n",
    "        mass (float): Particle mass (kg)\n",
    "        velocity (float): Particle velocity (m/s)\n",
    "        \n",
    "    Returns:\n",
    "        (float): Particle kinetic energy (J)\n",
    "    \"\"\"\n",
    "    kinetic_energy = 0.5 * mass * velocity ** 2\n",
    "    return kinetic_energy"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Above, the function has been given the name `kinetic_energy` and takes two arguments; `mass` and `velocity`, the kinetic energy is then found and *returned*.\n",
    "\n",
    "Following definition, the function may be used as follows,"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2020-04-05T15:05:58.355407Z",
     "start_time": "2020-04-05T15:05:58.349328Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "450000.0\n"
     ]
    }
   ],
   "source": [
    "print(kinetic_energy(10, 300))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The function above has been called with the variables `mass=10` and `velocity=30`. \n",
    "Within the function, the following steps are occuring,\n",
    "```\n",
    ">>> kinetic_energy = 0.5 * mass * velocity ** 2\n",
    ">>> kinetic_energy = 0.5 * 10 * 300 ** 2\n",
    ">>> kinetic_energy = 450000.0\n",
    "\n",
    ">>> return kinetic_energy\n",
    ">>> return 450000.0\n",
    "```\n",
    "The kinetic energy value then *returned* by the function, and in the case above passed to the `print()` function. \n",
    "Hence, it is printed to the screen.\n",
    "\n",
    "## Defining a function\n",
    "\n",
    "Having seen, generally, how functions work, let's go into a bit more detail of function declaration, \n",
    "\n",
    "<center>\n",
    "    <img src=\"../images/a_function.png\" width=45%>\n",
    "    <br>\n",
    "    <i>\n",
    "        Figure 1. The anatomy of a simple Python function.\n",
    "    </i>\n",
    "</center>\n",
    "\n",
    "The function consists of four main textual areas:\n",
    "\n",
    "- **Definition**: Beginning with `def`, this is where the name and arguments for the function are defined\n",
    "- **Docstring**: This contains information about what the particular function does, including the arguments and what is returned\n",
    "- **Content**: Where the code of the function lives\n",
    "- **Return**: The information that is returned from the function, using the `return` keyword.\n",
    "\n",
    "<hr>\n",
    "<hr>\n",
    "\n",
    "#### Aside: whitespace\n",
    "\n",
    "Python takes whitespace **seriously**. \n",
    "It is used for idenifying a *block*; such as a function. \n",
    "The function content begins when the indented section starts and ends when the indentation is removed. \n",
    "In Figure 1, the docstring, content and return of the function are all within this *block*, if the whitespace is removed then Python will consider the function to be completed at this point. \n",
    "The indentation can be any length (although 4 spaces is a [PEP8 Standard](https://www.python.org/dev/peps/pep-0008/#indentation)) but needs to be consistent. \n",
    "Throughout this book, we will see a few examples of other *blocks* (such as loops and if-statement), when you come across these note the importance of the whitespace that is used to define the block. \n",
    "\n",
    "<hr>\n",
    "<hr>\n",
    "\n",
    "### Definition\n",
    "\n",
    "A function is defined using the keyword `def`, which tells the Python interperator that in that line you will be giving a function name followed by a set of brackets, some arguments (although these are not essential), and a colon. \n",
    "The function name *needs* to be a single continuous string of characters with no whitespace between them, a common convention is to use the `_` (underscore) character to denote where there should be a space. \n",
    "Note, `kinetic_energy` above. \n",
    "\n",
    "The number of arguments that a function may have can be anything from 0 to infinity (although that is obviously impractical). \n",
    "If a function is to have no arguments, it will simply have the open and closed brackets immediately following the function definition with nothing inside them. \n",
    "\n",
    "In addition to arguments, a function may also have *keyword arguments*. \n",
    "These are arguments that are defined with a *default* value which may be changed when the function is called. \n",
    "An example of this is shown below, "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2020-04-05T15:05:58.366916Z",
     "start_time": "2020-04-05T15:05:58.360608Z"
    }
   },
   "outputs": [],
   "source": [
    "def beer_lambert(epsilon, absorbance, path_length=1.):\n",
    "    \"\"\"\n",
    "    Evaluate the concentration of a solution, using the Beer-Lambert law.\n",
    "    \n",
    "    Args:\n",
    "        epsilon (float): Molar attenuation coefficient (L/(mol cm))\n",
    "        absorbance (float): Absorbance of the solution\n",
    "        path_lenght (float, optional): Distance travelled through the sample (cm).\n",
    "    \n",
    "    Returns:\n",
    "        (float): Concentration of solution (mol/L)\n",
    "    \"\"\"\n",
    "    concentration = absorbance / (epsilon * path_length)\n",
    "    return concentration"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In the Beer-Lambert law function above, the path length is assumed to be 1 cm if no other value is given (this is because most spectroscopic curvettes are 1 cm wide). \n",
    "This means that there are now, two possible way to run the function above. \n",
    "\n",
    "**If** the path length is 1 cm, the following is run,"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2020-04-05T15:05:58.376579Z",
     "start_time": "2020-04-05T15:05:58.370908Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.009523809523809525\n"
     ]
    }
   ],
   "source": [
    "print(beer_lambert(21000, 200))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Else** the path length is some other value (in the example below 10 cm), then the following is run."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2020-04-05T15:05:58.385133Z",
     "start_time": "2020-04-05T15:05:58.379417Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.0009523809523809524\n"
     ]
    }
   ],
   "source": [
    "print(beer_lambert(21000, 200, path_length=10))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "While it makes the code clearer, the `path_length` keyword does not **need** to be included, so the following will also run,"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2020-04-05T15:05:58.396493Z",
     "start_time": "2020-04-05T15:05:58.388479Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.0009523809523809524\n"
     ]
    }
   ],
   "source": [
    "print(beer_lambert(21000, 200, 10))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Docstring\n",
    "\n",
    "The docstring is an important (although not essential) component of any function. \n",
    "Describing the purpose of a function is valuable of many reasons, it helps to clarify **what** the function will do, it offers guidence for others on how to use the function, and it acts to remind *future you* why it is that you have a particular function and what is does. \n",
    "You may read this last point and roll your eyes, however I promise you that code you write today will not stay present in your memory forever. \n",
    "\n",
    "In addition to a description of the function, a docstring also typically includes information about the arguments taken by the function and objects that are returned. \n",
    "There are a few common way that these may be formatted, within this book we will use [Google Style](https://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html), however, other styles exist, such as NumPy and Sphinx. \n",
    "Using a standard style of docstring is useful when writting large software packages, due to the availablity of tools to automatically generate software documentation from these docstrings.\n",
    "The Google style indicates the arguments with the keyword `Args`, before listing the arguments, the expected type and a short description (we find that it can be helpful to include information about the expected units in this section). \n",
    "The `Returns` keyword is followed by a list of the values returned by the function, since these do not necessary has a *name* this is omitted. \n",
    "\n",
    "### Content\n",
    "\n",
    "The content of the function is relatively straightforward, it is the code that means the function **does** something. \n",
    "However, this is a good chance to mention *scope*, the scope of a variable is the area in the code that it can be used.\n",
    "A variable that is created inside a function **cannot** be used elsewhere in your program, this includes the arugment variables. \n",
    "However, it is possible to make use of a variable defined outside of a function within it, just remember that a piece of Python code is parsed from top-to-bottom so the variable needs to be defined **before** the function. \n",
    "See below for an example of this in action, "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2020-04-05T15:05:58.412833Z",
     "start_time": "2020-04-05T15:05:58.406826Z"
    }
   },
   "outputs": [],
   "source": [
    "speed_of_light = 2.99792458e8\n",
    "planck = 6.62607004e-34\n",
    "\n",
    "def photon_energy(wavelength):\n",
    "    \"\"\"\n",
    "    Determines the energy of a single photon with a given wavelength.\n",
    "    \n",
    "    Args:\n",
    "        wavelength (float): Photon wavelength (m)\n",
    "    \n",
    "    Returns:\n",
    "        (float): Photon energy (J)\n",
    "    \"\"\"\n",
    "    return planck * speed_of_light / wavelength"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2020-04-05T15:05:58.422159Z",
     "start_time": "2020-04-05T15:05:58.416631Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "3.310743040286264e-19\n"
     ]
    }
   ],
   "source": [
    "print(photon_energy(600e-9))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Return\n",
    "\n",
    "The return statement is the keyword that tells the Python interpertor to stop the function and *return* the value(s) given.\n",
    "You will note in the `photon_energy()` function above, there is a mathematical operation on the `return` line. \n",
    "This is fine as the mathematics will be carried out before the value is returned. \n",
    "\n",
    "It is possible return more than one variable from a function.\n",
    "These will be returned as a `tuple` of variables, which may require unpacking as appropriate. \n",
    "An example where more than one variable is returned is shown below, "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2020-04-05T15:05:58.430872Z",
     "start_time": "2020-04-05T15:05:58.425618Z"
    }
   },
   "outputs": [],
   "source": [
    "speed_of_light = 2.99792458e8\n",
    "planck = 6.62607004e-34\n",
    "\n",
    "def photon_energy(wavelength):\n",
    "    \"\"\"\n",
    "    Determines the energy of a single photon with a given wavelength in both\n",
    "    Joules and electron volts.\n",
    "    \n",
    "    Args:\n",
    "        wavelength (float): Photon wavelength (m)\n",
    "    \n",
    "    Returns:\n",
    "        (tuple of length 2, float): Photon energy in J and eV respectively\n",
    "    \"\"\"\n",
    "    energy = planck * speed_of_light / wavelength\n",
    "    return energy, energy * 6.242e+18"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2020-04-05T15:05:58.442191Z",
     "start_time": "2020-04-05T15:05:58.436870Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(3.310743040286264e-19, 2.066565805746686)\n"
     ]
    }
   ],
   "source": [
    "print(photon_energy(600e-9))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2020-04-05T14:46:09.988684Z",
     "start_time": "2020-04-05T14:46:09.976509Z"
    }
   },
   "source": [
    "The function `kinetic_energy`, introduced earlier, calculates the kinetic energy given the mass and velocity of a particle. \n",
    "\n",
    "**Exercise:** Write a function that returns the momentum of a particle given the particle's mass and velocity. Recall that\n",
    "\n",
    "$$\n",
    "p = mv.\n",
    "$$\n",
    "\n",
    "Following this write another function that uses this momentum to calculate the kinetic energy of the particle using\n",
    "\n",
    "$$\n",
    "E_{kin} = \\frac{p^{2}}{2m}.\n",
    "$$\n",
    "\n",
    "Check your kinetic energy function using the `kinetic_energy` function. Ensure that your functions have appropriate docstrings so that other users can use your functions. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2020-04-05T15:05:58.449331Z",
     "start_time": "2020-04-05T15:05:58.445387Z"
    }
   },
   "outputs": [],
   "source": [
    "### Write your code here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
