{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Functions\n", "\n", "## Motivation\n", "Often we find ourselves repeating code or a computation multiple times\n", "with slightly different values or on different pieces of data.\n", "\n", "For instance, consider a program with the task of printing out\n", "the happy birthday song. Let's start by writing this program to print\n", "out happy birthday to \"Alice\":" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(\"Happy birthday to you\")\n", "print(\"Happy birthday to you\")\n", "print(\"Happy birthday to Alice\")\n", "print(\"Happy brithday to you\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now, if we wanted to print happy birthday to somebody\n", "else, we could copy this whole block of code and change\n", "the name. Let's go ahead and do that to sing happy birthday\n", "to Bob." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(\"Happy birthday to you\")\n", "print(\"Happy birthday to you\")\n", "print(\"Happy birthday to Bob\")\n", "print(\"Happy brithday to you\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Oops! We spelled birthday wrong in the last line,\n", "to fix it we now have 2 places to correct the mistake.\n", "This isn't that bad, but imagine instead if we had made\n", "10 copies to print happy birthday to 10 different people.\n", "Or worse, what if we didn't remember how many times we had\n", "copied it when we found the mistake.\n", "\n", "In general, copying and pasting code is a bad thing to do,\n", "this should generally be an indication that you may want to\n", "take a different approach. More specifically, when you repeat\n", "code, that often means you may want to consider using a **function**.\n", "\n", "We've already seen one example of a function, the `print()` function\n", "that prints out it's arguments. But, we can also design our own\n", "functions.\n", "\n", "## What is a function?\n", "A function is simply a grouped sequence of statements with a name.\n", "\n", "## Why use a function?\n", "\n", "* Decomposition: Take a larger, complex problem and break it up\n", " into smaller individual parts. This can actually make it easier\n", " to program because the goal is no longer to program the entire\n", " solution, but instead to work on each of the individual pieces.\n", " A single function might be one of many in the problem decomposition.\n", "* Abstraction: Focus on the general aspects, ignoring the\n", " individual details to identify common aspects. \n", " \n", "## What does a function look like?\n", "```\n", "def function_name(parameter1, parameter2, ...):\n", " # Code for the function body would go below this comment\n", "\n", " return somevalue\n", "```\n", "\n", "Note that this is just a **function definition** (hence the use\n", "of the keyword `def`. Defining\n", "a function doesn't actually do anything with it -- recall it just\n", "gives a name to the sequence of statements. Let's look a little\n", "closer at the parts of the function definition:\n", "\n", "* name: the name we will use to call our function\n", "* parameters: the external values needed to perform the computation\n", "* body: the statements to be executed\n", "* return: the computed results that need to be accessible\n", " after the function finishes. (optional, without a return\n", " statement the default return value is `None`)\n", "\n", "To actually use\n", "the function, we need to **call** the function. We do this\n", "by:\n", "```\n", "function_name(argument1, argument2, ...)\n", "```\n", "Note that the `...` isn't a technical python notation, this\n", "just means with the appropriate number of arguments (based on\n", "however many parameters the function accepts).\n", "\n", "### Argument vs Parameter\n", "Parameters are the identifiers used inside the function and\n", "a way of noting the items the function expects to receive.\n", "Arguments are the actual values passed into the function when\n", "it is called. These values are bound to the parameter names\n", "inside of the function.\n", "\n", "## Happy Birthday - Function Version\n", "Let's look at the simple happy birthday again. Really, all\n", "versions of these have the form:\n", "```\n", "print(\"Happy birthday to you\")\n", "print(\"Happy birthday to you\")\n", "print(\"Happy birthday dear NAME\")\n", "print(\"Happy birthday to you\")\n", "```\n", "This would be an idea of abstraction, the name isn't critical\n", "to the general idea of what we need to do.\n", "\n", "Let's go ahead and look at what this looks like as a function:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def happy_birthday_song(name):\n", " print(\"Happy birthday to you\")\n", " print(\"Happy birthday to you\")\n", " print(\"Happy birthday dear\", name)\n", " print(\"Happy birthday to you\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note, that when we ran the previous cell it didn't actually print out anything. Remember, that is expected as that\n", "was just the function definition. To actually print out happy birthday, we would need to call the function:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "happy_birthday_song(\"Alice\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "happy_birthday_song(\"Bob\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Removing More Repetition\n", "Even in our function version of happy birthday, we still\n", "have some repeated code. In the idea of problem\n", "decomposition, we could break this down into a smaller\n", "aspects (say \"happy birthday to you\") that occurs three times.\n", "So, we could pull this out into it's own function as well\n", "and call that from within the `happy_birthday_song` function\n", "to reduce repeated code. \n", "\n", "Note, that the function to replace the single line doesn't need\n", "arguments since it does not depend on any values." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def happy_birthday():\n", " print(\"Happy birthday to you\")\n", "\n", "def happy_birthday_song(name):\n", " happy_birthday()\n", " happy_birthday()\n", " print(\"Happy birthday dear\", name)\n", " happy_birthday()\n", "\n", "happy_birthday_song(\"Alice\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Default Values\n", "Often we want to write a function for which some (or all)\n", "of the parameters have default values that apply if no value is\n", "passed in for that parameter. We can do this easily in Python.\n", "Let's look at our birthday example. Suppose we want the default\n", "to be to sing happy birthday to Alice. We can specify this by:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def happy_birthday():\n", " print(\"Happy birthday to you\")\n", "\n", "def happy_birthday_song(name=\"Alice\"):\n", " happy_birthday()\n", " happy_birthday()\n", " print(\"Happy birthday dear\", name)\n", " happy_birthday()\n", "\n", "happy_birthday_song()\n", "happy_birthday_song(\"Bob\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's look at what happens now when we call `happy_birthday_song`\n", "without an argument:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "happy_birthday_song()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Quadratic Formula Example\n", "\n", "Let's look at another example of where a function may be useful.\n", "Recall that the quadratic formula\n", "$$\\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a}$$\n", "can be used to find the roots of a quadratic equation $ax^2 + bx + c$.\n", "This is another example of abstraction: the precise values\n", "for $a$, $b$, and $c$ don't change the computations we need to perform.\n", "\n", "Note that in this example we need to return a value. To do this,\n", "we simply add a `return` statement at the end of our function.\n", "\n", "Let's start by assuming\n", "we only care about computing the root with the $+$ and we'll test it\n", "on $$x^2 + 2x - 15.$$" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def quadratic_formula(a, b, c):\n", " temp = (b**2 - 4*a*c)**0.5\n", " return (-b + temp)/(2*a)\n", "\n", "coeffx2 = 1\n", "coeffx = 2\n", "coeff1 = -15\n", "root1 = quadratic_formula(coeffx2, coeffx, coeff1)\n", "print(root1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "What if we had wanted to compute and return both roots?\n", "Thankfully, python is very flexible and allows you to return\n", "as many values as you'd like (most languages are not this flexible).\n", "To do so, we simply separate the values to be returned by commas in\n", "the `return` statement. Let's adapt this function to return both:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def quadratic_formula(a, b, c):\n", " temp = (b**2 - 4*a*c)**0.5\n", " return (-b + temp)/(2*a), (-b - temp)/(2*a)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We need to make one additional modification when calling\n", "the function -- we need to store both results. We do this\n", "through a process called *unpacking* where we simply have multiple\n", "identifiers on the left side that we use to assign the different\n", "values to (need to have the same number of variables as we have values\n", "returned). For example," ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "root1, root2 = quadratic_formula(coeffx2, coeffx, coeff1)\n", "print(root1)\n", "print(root2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Keyword Arguments\n", "The examples so far have all relied on *positional arguments*.\n", "This means that the position (aka order) of the arguments is used\n", "to determine which argument ends up as the value of each parameter\n", "inside the function. For instance, python knew that 1 is supposed\n", "to be the value for `a` inside the function, because 1 is the first\n", "argument and `a` is the first parameter.\n", "\n", "Sometimes, it can be helpful to explicitly indicate which parameter\n", "the argument should be assigned to. This is called keyword arguments\n", "and means that those arguments do not rely on the order they are passed\n", "in. You don't need to worry much about these now, but we'll see them\n", "at various points throughout the course. \n", "\n", "Let's just look at the simple\n", "example of quadratic formula to see what this means. When we\n", "called the function above, we passed in the values for `a`, `b`, and `c`\n", "in the order they were listed. We could have instead done (or any other\n", "order) because we explicitly say which value is for each parameter." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "root1, root2 = quadratic_formula(c=-15, a=1, b=2)\n", "print(root1)\n", "print(root2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Technically keyword and positional can be mixed, but for now you should assume that for most user defined functions, it is best to stick with all positional or all keyword." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Scope\n", "\n", "Once we start working with functions, it's important to\n", "understand the idea of scope. Scope indicates\n", "where a given variable is accessible. Variables defined\n", "in a function body (and the parameter names) are only\n", "accessible within the function (aka local scope).\n", "\n", "This means that once the function returns, all the variables\n", "inside the function go away, unless they are returned and\n", "stored in a variable back outside of the function.\n", "\n", "Technically, functions can access variables defined outside\n", "of the function as long as they are defined before the function\n", "is called. While there are good reasons for taking advantage of\n", "this, in many cases it will likely be improperly used and cause\n", "confusion. So, for now you should not rely on this and should\n", "instead design your function to accept any data it needs as\n", "arguments." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Docstrings\n", "Python has a default way to provide information\n", "about what a function does. This is through the `help`\n", "function. Let's look at `help` for `print`:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "help(print)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Built-in functions have the output for the help command\n", "predefined. For user-defined functions (functions we\n", "create ourselves), we can easily provide this message\n", "through the use of docstrings. Docstrings are triple-quoted\n", "strings immediately inside the body of the function, before\n", "any other code that describe what the function does,\n", "what its arguments are, and what it returns. While\n", "not required (our functions early ran fine without them),\n", "they can be helpful for others who may be using your code.\n", "\n", "Let's add a docstring for the quadratic formula function:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def quadratic_formula(a, b, c):\n", " \"\"\"\n", " Computes solutions of ax^2 + bx + c = 0.\n", "\n", " Parameters: coefficients a, b, and c of equation\n", " Returns: the 2 solutions of the equation\n", " \"\"\"\n", " temp = (b**2 - 4*a*c)**0.5\n", " return (-b + temp)/(2*a), (-b - temp)/(2*a)\n", "\n", "help(quadratic_formula)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Built-In Functions" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Above, we looked at how to create\n", "our own functions (known as user-defined functions).\n", "\n", "\n", "There are also quite a few functions built-in to python.\n", "Some of these [built-in functions are in the base part of python](https://docs.python.org/3/library/functions.html),\n", "meaning you can simply call them. We've already seen a few of these functions:\n", "\n", "* `print()` - prints arguments\n", "* `help()` - help page printed for the argument\n", "* `type()` - returns the type of the argument\n", "\n", "## Print\n", "\n", "This function prints the arguments passed to it. It can\n", "print a single object, or it can be called with multiple objects\n", "in which case it prints all of them (by default separated by a space).\n", "We can see more details for this function by looking at the\n", "[documentation for print()](https://docs.python.org/3/library/functions.html#print).\n", "All aspects of base python, and the vast majority of all available\n", "python will have documentation -- essentially web pages with the function signature\n", "(aka, what parameters it accepts), a description of the function, and often examples\n", "of calling the function. It's good to get used to looking at the docs as they\n", "are the definitive guide to the language. Looking at the docs we see we\n", "can pass a keyword argument `sep` to use a different separator.\n", "For example:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "x = 4\n", "y = 5\n", "print(x,y)\n", "print(x,y, sep=\",\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Notice how the second one did not print a space in between, but instead separated\n", "the two values being printed with a comma (the character indicated for `sep`).\n", "\n", "## Type Conversion\n", "Some of the built-in functions are used to convert between different types we\n", "have previously discussed. For instance, `int()` is designed to take it's\n", "argument and turn it into an int (by truncating towards 0)." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "a = 15.6\n", "b = int(a)\n", "print(b)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Likewise, there are `bool()`, `str()`, `float()`, and `complex()` to convert to boolean, string, float, and complex types, respectively." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "a_string = str(a)\n", "print(type(a))\n", "print(type(a_string))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Other Helpful Built-in Functions\n", "Many of the other (non-type conversion) functions can also be useful.\n", "For now we'll highlight a few of them:\n", "\n", "* `abs()` - Return the absolute value of a number (float or integer).\n", " For complex numbers, returns it's magnitude.\n", "* `min()` - return the minimum of the arguments\n", "* `max()` - return the maximum of the arguments\n", "* `round()` - round the number (1st argument) to the specified number of digits (2nd argument)\n", "* `len()` - returns the length of the string\n", "\n", "Let's look at some examples:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "x = -1.5\n", "y = 4\n", "z = 3 + 4j\n", "print(abs(x))\n", "print(abs(z))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(\"min =\", min(x,y))\n", "print(\"max =\", max(x,y))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "w = 1342.85998348\n", "print(round(w, 2))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "msg = \"hello how are you today\"\n", "print(len(msg))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note that although we simply printed the result after calling each of these functions, we could have also assigned the result to a variable." ] } ], "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.8.6" } }, "nbformat": 4, "nbformat_minor": 4 }