{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 42,
   "metadata": {
    "tags": [
     "remove_input"
    ]
   },
   "outputs": [],
   "source": [
    "path_data = '../../data/'\n",
    "path_data = '../../image/'\n",
    "\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "\n",
    "%matplotlib inline\n",
    "import matplotlib.pyplot as plt\n",
    "plt.style.use('fivethirtyeight')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 8. Functions and Tables"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "(**N.B.** when using the term 'Table(s)' we are referring to DataFrames)\n",
    "\n",
    "We are building up a useful inventory of techniques for identifying patterns and themes in a data set by using functions already available in Python. We will now explore a core feature of the Python programming language: function definition.\n",
    "\n",
    "We have used functions extensively already in this text, but never defined a function of our own. The purpose of defining a function is to give a name to a computational process that may be applied multiple times. There are many situations in computing that require repeated computation. For example, it is often the case that we want to perform the same manipulation on every value in a column of a table."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Defining a Function\n",
    "The definition of the `double` function below simply doubles a number."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Our first function definition\n",
    "\n",
    "def double(x):\n",
    "    \"\"\" Double x \"\"\"\n",
    "    return 2*x"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We start any function definition by writing `def`.  Here is a breakdown of the other parts (the *syntax*) of this small function:\n",
    "\n",
    "![](../../images/function_definition.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "When we run the cell above, no particular number is doubled, and the code inside the body of `double` is not yet evaluated.  In this respect, our function is analogous to a *recipe*.  Each time we follow the instructions in a recipe, we need to start with ingredients.  Each time we want to use our function to double a number, we need to specify a number.\n",
    "\n",
    "We can call `double` in exactly the same way we have called other functions. Each time we do that, the code in the body is executed, with the value of the argument given the name `x`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "34"
      ]
     },
     "execution_count": 30,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "double(17)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "-0.3"
      ]
     },
     "execution_count": 31,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "double(-0.6/4)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The two expressions above are both *call expressions*. In the second one, the value of the expression `-0.6/4` is computed and then passed as the argument named `x` to the `double` function. Each call expresson results in the body of `double` being executed, but with a different value of `x`.\n",
    "\n",
    "The body of `double` has only a single line:\n",
    "\n",
    "`return 2*x`\n",
    "\n",
    "Executing this *`return` statement* completes execution of the `double` function's body and computes the value of the call expression.\n",
    "\n",
    "The argument to `double` can be any expression, as long as its value is a number.  For example, it can be a name.  The `double` function does not know or care how its argument is computed or stored; its only job is to execute its own body using the values of the arguments passed to it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "84"
      ]
     },
     "execution_count": 32,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "any_name = 42\n",
    "double(any_name)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The argument can also be any value that can be doubled. For example, a whole array of numbers can be passed as an argument to `double`, and the result will be another array."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([ 6,  8, 10])"
      ]
     },
     "execution_count": 33,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "double(np.array([3, 4, 5]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "However, names that are defined inside a function, including arguments like `double`'s `x`, have only a fleeting existence.  They are defined only while the function is being called, and they are only accessible inside the body of the function. We can't refer to `x` outside the body of `double`. The technical terminology is that `x` has *local scope*.\n",
    "\n",
    "Therefore the name `x` isn't recognized outside the body of the function, even though we have called `double` in the cells above."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {
    "tags": [
     "raises-exception"
    ]
   },
   "outputs": [
    {
     "ename": "NameError",
     "evalue": "name 'x' is not defined",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mNameError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-34-6fcf9dfbd479>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mx\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[0;31mNameError\u001b[0m: name 'x' is not defined"
     ]
    }
   ],
   "source": [
    "x"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Docstrings.** Though `double` is relatively easy to understand, many functions perform complicated tasks and are difficult to use without explanation. (You may have discovered this yourself!) Therefore, a well-composed function has a name that evokes its behavior, as well as documentation.  In Python, this is called a *docstring* — a description of its behavior and expectations about its arguments. The docstring can also show example calls to the function, where the call is preceded by `>>>`.\n",
    "\n",
    "A docstring can be any string, as long as it is the first thing in a function's body. Docstrings are typically defined using triple quotation marks at the start and end, which allows a string to span multiple lines. The first line is conventionally a complete but short description of the function, while following lines provide further guidance to future users of the function.\n",
    "\n",
    "Here is a definition of a function called `percent` that takes two arguments. The definition includes a docstring."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {},
   "outputs": [],
   "source": [
    "# A function with more than one argument\n",
    "\n",
    "def percent(x, total):\n",
    "    \"\"\"Convert x to a percentage of total.\n",
    "    \n",
    "    More precisely, this function divides x by total,\n",
    "    multiplies the result by 100, and rounds the result\n",
    "    to two decimal places.\n",
    "    \n",
    "    >>> percent(4, 16)\n",
    "    25.0\n",
    "    >>> percent(1, 6)\n",
    "    16.67\n",
    "    \"\"\"\n",
    "    return round((x/total)*100, 2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "16.5"
      ]
     },
     "execution_count": 36,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "percent(33, 200)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Contrast the function `percent` defined above with the function `percents` defined below. The latter takes an array as its argument, and converts all the numbers in the array to percents out of the total of the values in the array. The percents are all rounded to two decimal places, this time replacing `round` by `np.round` because the argument is an array and not a number."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {},
   "outputs": [],
   "source": [
    "def percents(counts):\n",
    "    \"\"\"Convert the values in array_x to percents out of the total of array_x.\"\"\"\n",
    "    total = counts.sum()\n",
    "    return np.round((counts/total)*100, 2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The function `percents` returns an array of percents that add up to 100 apart from rounding."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([33.33, 47.62, 19.05])"
      ]
     },
     "execution_count": 38,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "some_array = np.array([7, 10, 4])\n",
    "percents(some_array)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "It is helpful to understand the steps Python takes to execute a function.  To facilitate this, we have put a function definition and a call to that function in the same cell below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The biggest difference is 5\n"
     ]
    }
   ],
   "source": [
    "def biggest_difference(array_x):\n",
    "    \"\"\"Find the biggest difference in absolute value between two adjacent elements of array_x.\"\"\"\n",
    "    diffs = np.diff(array_x)\n",
    "    absolute_diffs = abs(diffs)\n",
    "    return max(absolute_diffs)\n",
    "\n",
    "some_numbers = np.array([2, 4, 5, 6, 4, -1, 1])\n",
    "big_diff = biggest_difference(some_numbers)\n",
    "print(\"The biggest difference is\", big_diff)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here is what happens when we run that cell:\n",
    "\n",
    "![Function_Execution](../../images/function_execution.jpg)\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Multiple Arguments"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "There can be multiple ways to generalize an expression or block of code, and so a function can take multiple arguments that each determine different aspects of the result. For example, the `percents` function we defined previously rounded to two decimal places every time. The following two-argument definition allows different calls to round to different amounts."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Rounded to 1 decimal place:  [28.6 14.3 57.1]\n",
      "Rounded to 2 decimal places: [28.57 14.29 57.14]\n",
      "Rounded to 3 decimal places: [28.571 14.286 57.143]\n"
     ]
    }
   ],
   "source": [
    "def percents(counts, decimal_places):\n",
    "    \"\"\"Convert the values in array_x to percents out of the total of array_x.\"\"\"\n",
    "    total = counts.sum()\n",
    "    return np.round((counts/total)*100, decimal_places)\n",
    "\n",
    "parts = np.array([2, 1, 4])\n",
    "print(\"Rounded to 1 decimal place: \", percents(parts, 1))\n",
    "print(\"Rounded to 2 decimal places:\", percents(parts, 2))\n",
    "print(\"Rounded to 3 decimal places:\", percents(parts, 3))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The flexibility of this new definition comes at a small price: each time the function is called, the number of decimal places must be specified. Default argument values allow a function to be called with a variable number of arguments; any argument that isn't specified in the call expression is given its default value, which is stated in the first line of the `def` statement. For example, in this final definition of `percents`, the optional argument `decimal_places` is given a default value of 2."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Rounded to 1 decimal place: [28.6 14.3 57.1]\n",
      "Rounded to the default number of decimal places: [28.57 14.29 57.14]\n"
     ]
    }
   ],
   "source": [
    "def percents(counts, decimal_places=2):\n",
    "    \"\"\"Convert the values in array_x to percents out of the total of array_x.\"\"\"\n",
    "    total = counts.sum()\n",
    "    return np.round((counts/total)*100, decimal_places)\n",
    "\n",
    "parts = np.array([2, 1, 4])\n",
    "print(\"Rounded to 1 decimal place:\", percents(parts, 1))\n",
    "print(\"Rounded to the default number of decimal places:\", percents(parts))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Note: Methods\n",
    "Functions are called by placing argument expressions in parentheses after the function name. Any function that is defined in isolation is called in this way. You have also seen examples of methods, which are like functions but are called using dot notation, such as `some_table.sort_values(some_label)`. The functions that you define will always be called using the function name first, passing in all of the arguments.  \n",
    "\n",
    "**N.B.** remember - a table is another name for a df"
   ]
  }
 ],
 "metadata": {
  "anaconda-cloud": {},
  "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.6.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
