{ "cells": [ { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Programming with Python\n", "#### Stefan Güttel, [guettel.com](http://guettel.com)\n", "\n", "## Contents:\n", "\n", "1. Functions" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Functions\n", "\n", "Functions are an extremely important programming concept for structuring your code and avoiding repetitions. And you will use them extensively in the upcoming lab tests and also in the final coursework. So let's dive in!\n", "\n", "We have previously seen a code similar to the one below, while discussing various problems arising with floating point operations on a computer:" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "slideshow": { "slide_type": "-" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "n = 7\n", "Fn = 13\n" ] } ], "source": [ "n = int(input(\"n = \"))\n", "f0 = 0\n", "f1 = 1\n", "while n > 1:\n", " nxt = f0 + f1\n", " f0 = f1\n", " f1 = nxt\n", " n -= 1\n", "print(\"Fn =\", f1)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "-" } }, "source": [ "This code inputs an integer n for which it computes and prints the $n^{\\rm th}$ Fibonacci number." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here is how we can analyze it:\n", "\n", "1. We first initialize (set to their starting values) variables f0 and f1 to 0 and 1 respectively.\n", "\n", "2. Then we run a loop as long as n > 1. In that loop, we\n", "\n", " 2.1. Compute the sum f0 + f1 and save it for later in the variable nxt (short of \"next\", which we don't use because next is a built-in Python function).\n", "\n", " 2.2. We assign f0 = f1 and f1 = nxt. \n", " In other words, the new value of f0 is equal to the old value of f1 and the new value is equal to the sum of **old** values of f0 and f1.\n", "\n", " 2.3. We reduce n by 1." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "Notice how n is changed exactly once in each pass through the loop and nowhere else. This means that our variable n has the following values throughout the loop: \n", "$n \\rightarrow n - \\color{red}{1}$ (the $\\color{red}{1}^{\\rm st}$ pass; drops to $n-\\color{red}{1}$ in the last step of the loop), \n", "$n-1 \\rightarrow n - \\color{red}{2}$ (the $\\color{red}{2}^{\\rm nd}$ pass; drops to $n-\\color{red}{2}$ in the last step of the loop), \n", "$n-2 \\rightarrow n - \\color{red}{3}$ (the $\\color{red}{3}^{\\rm rd}$ pass; drops to $n-\\color{red}{3}$ in the last step of the loop), \n", "... \n", "$n-k+1 \\rightarrow n - \\color{red}{k}$ (the $\\color{red}{k}^{\\rm th}$ pass; drops to $n-\\color{red}{k}$ in the last step of the loop), \n", "...\n", "\n", "The loop will stop when the current value of n no longer satisfies the condition n > 1. Given that our variable drops by 1 in each step, this will happen when it drops to exactly 1. In other words, when variable n gets the value 1 = n - k, which happens at the end step number $k = n-1$ (where $n$ is the starting value of the variable n).\n", "\n", "Given that f0 =  $\\ F_0$ and f1 =  $\\ F_1$ are the zeroth and the first Fibonacci numbers, and all subsequent ones are the sum of the previous two (nxt = f0 + f1), we conclude that the above code produces the Fibonacci numbers. How many of them?\n", "\n", "Each loop pass produces one Fibinacci number (in the first pass we get $F_2$, then in the second we get $F_3$, etc.) and we have just concluded that we do this $k = n - 1$ times. In other words, when we're done, f1 contains the value $F_n$." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## From a \"regular\" code to a function\n", "\n", "Now, computing the $n^{\\rm th}$ Fibonacci number is sometimes useful and it would be really neat to write it once and then (re)use it throughout the code. This is achieved using **functions**.\n", "\n", "Here is the previously displayed code, wrapped in a function:" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "slideshow": { "slide_type": "-" } }, "outputs": [], "source": [ "def fibonacci(n):\n", " \"\"\"\n", " Takes one argument n and returns the n-th Fibonacci number.\n", " \"\"\"\n", " f0 = 0\n", " f1 = 1\n", " while n > 1:\n", " nxt = f0 + f1\n", " f0 = f1\n", " f1 = nxt\n", " n -= 1\n", " return f1" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "Here are the main elements:\n", "\n", "1. Function declaration, consisting of these elements:\n", " 1. the keyword def;\n", " 2. the name of the function;\n", " 3. the list of the *formal parameters* that the function takes, enclosed in brackets. \n", " The brackets have to be there, even if the function takes no arguments.\n", " 4. a colon (as always when we are starting a block).\n", " \n", "2. A so called *docstring* -- an explanation what the function does, enclosed in a pair of triple quotation marks. This is a fairly pythonic thing that exists in some form in only a handful of other languages (PERL, for example). \n", " Recall that we've seen these last week, and we're putting them in the beginning of all programs. \n", " While technically not mandatory, it is a good practice to thoroughly comment your parts of your code in Python (all the functions, classes, modules, etc.). \n", " \n", "3. The body of the function: this is the code that is executed when the function is envoked. It is pretty much the same as the \"regular\" code, apart from the occasional return statement.\n", "\n", "4. The return statement does two equally important tasks:\n", " 1. It **interrupts the execution** of the function.\n", " 2. It provides the function's return value.\n", "\n", "Notice how running the above code does seemingly nothing. It actually creates a function, which we can then call..." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Calling a function\n", "\n", "This is as straightforward as one would expect:" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "slideshow": { "slide_type": "-" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "n = 7\n", "F(7) = 13\n" ] } ], "source": [ "n = int(input(\"n = \"))\n", "f = fibonacci(n)\n", "print(\"F(\" + str(n) + \") =\", f)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "or" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "slideshow": { "slide_type": "-" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "n = 7\n", "F(7) = 13\n" ] } ], "source": [ "n = int(input(\"n = \"))\n", "print(\"F(\" + str(n) + \") =\", fibonacci(n))" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "In the call fibonacci(n), the variable n is called the *actual parameter* or *argument*. Even though it has the same name as the formal parameter, these two are *not* the same variable. Furthermore, the formal and the actual arguments need not have the same name. For example, these calls are all perfectly correct:" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "x = 7\n", "F(7) = 13\n", "F(17) = 1597\n", "F(13 + 17) = 832040\n", "F(x + 7) = F(14) = 377\n" ] } ], "source": [ "x = int(input(\"x = \"))\n", "print(\"F(\" + str(x) + \") =\", fibonacci(x))\n", "print(\"F(17) =\", fibonacci(17))\n", "print(\"F(13 + 17) =\", fibonacci(13 + 17))\n", "print(\"F(x + 7) = F(\" + str(x + 7) + \") =\", fibonacci(x + 7))" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### The parameters are (mostly) copies of the arguments\n", "\n", "Observe the following simple example:" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "17 19\n" ] } ], "source": [ "def inc(x, y):\n", " x += y\n", " return x\n", "\n", "a = 17\n", "b = inc(a, 2)\n", "print(a, b)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "As you can see, the value of a was not changed, even though the value of x was. This is because, when the function was called, x took the value of a (but it did not become a!), so the statement x += y changed only that copy, while (the original) a remained intact." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "To verify that the values of the *local variables* (i.e., those that \"belong\" to a function and are not visible outside of it) truly vanish when the function finishes, you can always try something like this:" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The first call:\n", "x = 17\n", "The second call:\n" ] }, { "ename": "UnboundLocalError", "evalue": "local variable 'x' referenced before assignment", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m\n\u001b[1;31mUnboundLocalError\u001b[0m Traceback (most recent call last)", "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[0;32m 7\u001b[0m \u001b[0mtest\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;32mTrue\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 8\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"The second call:\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 9\u001b[1;33m \u001b[0mtest\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;32mFalse\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[1;32m\u001b[0m in \u001b[0;36mtest\u001b[1;34m(defX)\u001b[0m\n\u001b[0;32m 2\u001b[0m \u001b[1;32mif\u001b[0m \u001b[0mdefX\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 3\u001b[0m \u001b[0mx\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;36m17\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 4\u001b[1;33m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"x =\"\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mx\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 5\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 6\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"The first call:\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", "\u001b[1;31mUnboundLocalError\u001b[0m: local variable 'x' referenced before assignment" ] } ], "source": [ "def test(defX):\n", " if defX:\n", " x = 17\n", " print(\"x =\", x)\n", "\n", "print(\"The first call:\")\n", "test(True)\n", "print(\"The second call:\")\n", "test(False)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "### Complex data structures\n", "\n", "When it comes to lists, sets, and other data structures, things get a bit more complex than \"their parameters are copies of the corresponding arguments\". We will explain this in detail when we discuss these structures." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## More on returning values\n", "\n", "Python also has a keyword yield that can be used to return list-like-objects (the same thing that for-loops like to use) in a special, memory efficient way. More on that when we learn about *generators*.\n", "\n", "In many programming languages, functions can return at most one value. In Python, however, a function can return as many values as we like. This will also be addressed later on.\n", "\n", "A function that ends without return or with just a return (no values given to be returned), will return None. In other programming languages, these may be called *void-functions* or *procedures*.\n", "\n", "If a function has more than one return statement (split between by an if branch or a similar mechanism), they need not return the same type or even the same number of values. However, be careful how these will be used (anyone calling the function must be aware of how many values are returned, what are their types, and what they represent; otherwise the return values will be useless).\n", "\n", "The return statement cannot be used outside of a function (it would have no meaning)." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "Consider the following two examples:" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "slideshow": { "slide_type": "-" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "a = 17\n", "b = 13\n", "Max1: 17.0\n", "Max2: 17.0\n" ] } ], "source": [ "def max1(x, y):\n", " \"\"\"\n", " Takes comparable values x and y as arguments.\n", " \n", " Returns the larger of the two, implemented with if-else.\n", " \"\"\"\n", " if x > y:\n", " return x\n", " else:\n", " return y\n", "\n", "def max2(x, y):\n", " \"\"\"\n", " Takes comparable values x and y as arguments.\n", " \n", " Returns the larger of the two, implemented with if (no else).\n", " \"\"\"\n", " if x > y:\n", " return x\n", " return y\n", "\n", "a = float(input(\"a = \"))\n", "b = float(input(\"b = \"))\n", "print(\"Max1:\", max1(a, b))\n", "print(\"Max2:\", max2(a, b))" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "-" } }, "source": [ "Can you find a and b such that these two functions return different values?" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Docstrings\n", "\n", "What is the use of these long explanations at the beginning of each function?\n", "\n", "They give valuable information to anyone using your function, without them being required to read the code of your function. If this so-called *docstring* precisely defines the input and output of your function, and what it does, anyone can use that function as a *black-box*. This is extremely powerful! For example, let's see what max1 from above does:" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", " Takes comparable values x and y as arguments.\n", " \n", " Returns the larger of the two, implemented with if-else.\n", " \n" ] } ], "source": [ "print(max1.__doc__)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "There is also a prettier version:" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on function max1 in module __main__:\n", "\n", "max1(x, y)\n", " Takes comparable values x and y as arguments.\n", " \n", " Returns the larger of the two, implemented with if-else.\n", "\n" ] } ], "source": [ "from pydoc import help\n", "help(max1)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "Doctrings are also commonly used to automatically generate a referrence manual for your code, using - for example - [Sphinx](http://sphinx-doc.org/)." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "Technically, docstrings are not *required* by Python and the functions will do just fine without them. However, they are a standard part of any Python code.\n", "\n", "**For this reason, make sure to write meaningful docstrings in the headers of ALL your programs and ALL your functions.**\n", "\n", "To grasp how important the docstrings are, take a look at the [list of projects using Sphinx](http://sphinx-doc.org/examples.html)." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "### Learn and do more\n", "\n", "The \"language\" used in docstrings is called *Markdown* and it is widely used for simple formatting of documents (for example, these lecture notes are written using Markdown). The documentation is easy to find, as are the editors for various platforms. Here are two on-line editors which working with various browsers:\n", "\n", "- [Markable](http://markable.in/editor/)\n", "- [Dillinger](http://dillinger.io/)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "### But what if I am the only one who will read this code?\n", "\n", "It doesn't matter. The *future you* (even as little as 6 months away) will likely not remember what the *present you* wrote. Between the two, there will be a lot of other work done, most of it probably unrelated to Python or even programming in general.\n", "\n", "**Always document your code!** Do not waste time on thinking if it is needed or not. It is. Always." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Default values of arguments\n", "\n", "Many times it is desirable to call the same function with different arguments (not just different values). For example, the function range (which we have seen earlier) can be called in several different ways:\n", "\n", "* range(m, n, s) -- numbers $m, m+s, \\dots, m + sk$, where $k \\in \\mathbb{N}$ such that $m + sk < n \\le m + s(k+1)$.\n", "* range(m, n) -- equivalent of range(m, n, 1). We say that the *default value* of step is $1$.\n", "* range(n) -- equivalent of range(0, n) or range(0, n, 1). In other words, the default value of start is $0$.\n", "\n", "The most obvious reason to do this is convenience: why calling range(0, n, 1) every few lines of the code if we can just write range(n) each time?" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "But there are other reasons as well. Instead of just using some fixed value as the default one, a function can perform complex tasks to determine what the value should be.\n", "\n", "For example, we could construct a function data(name) that retrieves some data (phone number, e-mail address, number of selfies uploaded to Facebook,...) about a person identified by name. If we omit name and just call data(), the function might check who is currently running the program and provide the data for that person. This is a *different* name for each person running the program, so not a simple matter of a constant." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "Let us observe an example: a function that returns the sum of all digits that, when divided by d, give the reminder r." ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [], "source": [ "def digit_sum(n, d, r):\n", " \"\"\"\n", " Return the sum of all the digits of an integer n that,\n", " when divided by d, give the reminder r.\n", "\n", " Parameters\n", " ----------\n", " n : int\n", " A number whose sum is computed.\n", " d : int\n", " The number by which each digit is to be divided. If d == 0, an error occurs.\n", " r : int\n", " The desired reminder of the division. If r < 0 or r >= d, the sum will be zero.\n", "\n", " Returns\n", " -------\n", " digit_sum : int\n", " The resulting sum of digits.\n", " \"\"\"\n", "\n", " # Initializations\n", " res = 0 # Result (do not use \"sum\", because there is a built-in function with that name)\n", " n = abs(n) # Lose the sign\n", "\n", " while n > 0:\n", " digit = n % 10\n", " if digit % d == r:\n", " res += digit\n", " n //= 10\n", "\n", " return res" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "**Note:** Notice the long docstring? This is how they should usually be written (description of what the function does, followed by the list of parameters and return values with types and descriptions). To avoid making these lecture notes unnecessarily long, we will usually not write docstrings in so much detail, but you are encouraged to do so in your own code.\n", "\n", "It is easy to call the above function. For example, to calculate the sum of all odd digits of a number, we call it as follows:" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "n = 12345\n", "9\n" ] } ], "source": [ "n = int(input(\"n = \"))\n", "print(digit_sum(n, 2, 1))" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "However, it might make sense to choose default values for some of the parameters. Which ones exactly, depends on the intended uses. In other words, you decide by yourself what makes the most sense.\n", "\n", "So, let us ask ourselves what would shorter calls to the function mean?\n", "\n", "* digit_sum(): no arguments, not even n; hard to imagine anything useful;\n", "* digit_sum(n): this could mean \"calculate the sum of **all** digits of n\"; this is equivalent to d = 1, r = 0;\n", "* digit_sum(n, d): only r is ommited; it makes sense to interpret this as \"calculate the sum of **all** digits of n that are divisible by d\"; this is equivalent to r = 0.\n", "\n", "Luckily, r has the same desired default value in both cases, so it is clear that r = 0 makes the most sense. Finally, our function (minus the docstring) might look like this:" ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "def digit_sum(n, d=1, r=0):\n", " \"\"\"\n", " ...\n", " \"\"\"\n", "\n", " # Initializations\n", " res = 0 # Result (do not use \"sum\", because there is a built-in function with that name)\n", " n = abs(n) # Lose the sign\n", "\n", " while n > 0:\n", " digit = n % 10\n", " if digit % d == r:\n", " res += digit\n", " n //= 10\n", "\n", " return res" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As you can see, only the function's declaration was changed, and in a very intuitive way:\n", "\n", "python\n", " def digit_sum(n, d=1, r=0):\n", "\n", "\n", "Here, d=1 means \"if the second argument's value was not given, set it to 1\".\n", "\n", "**A note on the writing style:** Both d = 1 and d=1 are, of course, correct. However, it is customary to not use spaces in function arguments assignments." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "Now, the calls to digit_sum can be:" ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "slideshow": { "slide_type": "-" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "n = 12345\n", "The sum of all digits of 12345 is 15\n", "The sum of all even digits of 12345 is 6\n", "The sum of all odd digits of 12345 is 9\n" ] } ], "source": [ "n = int(input(\"n = \"))\n", "print(\"The sum of all digits of\", n, \"is\", digit_sum(n))\n", "print(\"The sum of all even digits of\", n, \"is\", digit_sum(n, 2))\n", "print(\"The sum of all odd digits of\", n, \"is\", digit_sum(n, 2, 1))" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Limitations\n", "\n", "All the parameters can be given default values. However, one rule must be observed:\n", "> **All the parameters without a default value must appear before those that have a default value.**\n", "\n", "In other words, **this is invalid:**\n", "python\n", " def digit_sum(n = 17, d = 1, r):\n", "\n", "\n", "The reason is simple: what would digit_sum(5, 1) mean? While it is obvious that we want r = 1, it is unclear whether the value 5 should be assigned to n or d. With more parameters, much worse confusions could happen." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "That's why the parameters' values are assigned in order: the first given value is assigned to the first parameter, the second value to the second parameter, etc. Once we run out of values in the call of the function, the rest of the parameters are assigned their default values.\n", "\n", "If we have provided too few values when calling the function (for example, if we give no values when calling digit_sum), our function call will fail. For example:" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "digit_sum() missing 1 required positional argument: 'n'", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m\n\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mdigit_sum\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[1;31mTypeError\u001b[0m: digit_sum() missing 1 required positional argument: 'n'" ] } ], "source": [ "print(digit_sum())" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Named arguments\n", "\n", "This is Python-specific, but we mention it as it sometimes comes in handy. Consider a function:" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [], "source": [ "def pfv(a, b, c=3, d=4, e=5):\n", " \"\"\"\n", " Takes 5 parameters and prints them.\n", " The last three have a default value 3, 4, and 5 respectively.\n", " \n", " \"pfv\" stands for \"print five values\". :-)\n", " \"\"\"\n", " print(a, b, c, d, e)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "-" } }, "source": [ "As we have seen before, these calls are acceptable:" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "17 19 23 29 31\n", "17 19 23 29 5\n", "17 19 23 4 5\n", "17 19 3 4 5\n" ] } ], "source": [ "pfv(17, 19, 23, 29, 31)\n", "pfv(17, 19, 23, 29)\n", "pfv(17, 19, 23)\n", "pfv(17, 19)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "However, in Python we *can* keep default values for c and d while still giving a non-default value to e. Here is one such call:" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "17 19 3 4 31\n" ] } ], "source": [ "pfv(17, 19, e=31)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "We can even insist that some parameters must to be named:" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [], "source": [ "def pfv(a, b, c=3, *, d=4, e=5):\n", " \"\"\"\n", " ...\n", " \"\"\"\n", " print(a, b, c, d, e)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "Now, parameters after c must be named. Otherwise, an error occures:" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "pfv() takes from 2 to 3 positional arguments but 4 were given", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m\n\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mpfv\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m17\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;36m19\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;36m23\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;36m31\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[1;31mTypeError\u001b[0m: pfv() takes from 2 to 3 positional arguments but 4 were given" ] } ], "source": [ "pfv(17, 19, 23, 31)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "A proper call looks like this:" ] }, { "cell_type": "code", "execution_count": 21, "metadata": { "slideshow": { "slide_type": "-" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "17 19 23 31 5\n" ] } ], "source": [ "pfv(17, 19, 23, d=31)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "This allows us to define different calls of the same function with the same number and types of parameters, while still treating them differently." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Function calls as conditions\n", "\n", "What will the following code print?" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "False\n", "The cake is a lie.\n" ] } ], "source": [ "def f(x):\n", " \"\"\"\n", " Prints and returns x.\n", " \"\"\"\n", " print(x)\n", " return x\n", "\n", "if f(False) and f(True):\n", " print(\"The tooth is out there!\")\n", "else:\n", " print(\"The cake is a lie.\")" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "Obviously, \"The cake is a lie.\" got printed because the if line evaluates to if False and True which is equivalent to if False, so the program executes the else part.\n", "\n", "However, each call to f also prints the value that it is about to return. So, why is only False printed, and not True as well?" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "This happens because Python uses [*lazy evaluation*](http://en.wikipedia.org/wiki/Lazy_evaluation) of Boolean expressions. This means that once the result is uniquely determined, no further evaluation is done.\n", "\n", "On the shown example, we have f(False) and f(True). This is what happens during the evaluation:\n", "1. f(False) is executed. This results in printing of False and it returns False.\n", "2. Now, Python has False and f(True). However, False and ANYTHING is False, so Python doesn't bother with f(True) (whatever it returns, the whole expression would remain False). \n", " Therefore Python concludes that the whole expression is False, **without evaluating f(True)**, so True is never printed.\n", "3. Python now runs if False and enters the else branch, printing \"The cake is a lie.\"." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "Similarly, if f(True) or f(False) would not run f(False) because True or ANYTHING is True, regardless of the value of ANYTHING." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "Here is the whole set of True/False combinations for and and or:" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "f: False\n", "Expression 1 is false\n", "f: False\n", "Expression 2 is false\n", "f: True\n", "g: False\n", "Expression 3 is false\n", "f: True\n", "g: True\n", "Expression 4 is true.\n", "f: False\n", "g: False\n", "Expression 5 is false\n", "f: False\n", "g: True\n", "Expression 6 is true.\n", "f: True\n", "Expression 7 is true.\n", "f: True\n", "Expression 8 is true.\n" ] } ], "source": [ "def f(x):\n", " \"\"\"\n", " Prints and returns x.\n", " \"\"\"\n", " print(\"f:\", x)\n", " return x\n", "\n", "def g(x):\n", " \"\"\"\n", " Prints and returns x.\n", " \"\"\"\n", " print(\"g:\", x)\n", " return x\n", "\n", "if f(False) and g(False):\n", " print(\"Expression 1 is true.\")\n", "else:\n", " print(\"Expression 1 is false\")\n", "if f(False) and g(True):\n", " print(\"Expression 2 is true.\")\n", "else:\n", " print(\"Expression 2 is false\")\n", "if f(True) and g(False):\n", " print(\"Expression 3 is true.\")\n", "else:\n", " print(\"Expression 3 is false\")\n", "if f(True) and g(True):\n", " print(\"Expression 4 is true.\")\n", "else:\n", " print(\"Expression 4 is false\")\n", "\n", "if f(False) or g(False):\n", " print(\"Expression 5 is true.\")\n", "else:\n", " print(\"Expression 5 is false\")\n", "if f(False) or g(True):\n", " print(\"Expression 6 is true.\")\n", "else:\n", " print(\"Expression 6 is false\")\n", "if f(True) or g(False):\n", " print(\"Expression 7 is true.\")\n", "else:\n", " print(\"Expression 7 is false\")\n", "if f(True) or g(True):\n", " print(\"Expression 8 is true.\")\n", "else:\n", " print(\"Expression 8 is false\")" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "Of course, these expressions can be much more complex than just singe function calls." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "While it may look like a technical detail, lazy evaluation is often used without noticing it. For example:" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "a: 17\n", "b: 0\n", "17 is NOT divisible by 0\n" ] } ], "source": [ "a = int(input(\"a: \"))\n", "b = int(input(\"b: \"))\n", "if (b != 0 and a % b == 0):\n", " print(a, \"is divisible by\", b)\n", "else:\n", " print(a, \"is NOT divisible by\", b)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "Swapping the conditions in the above if can be catastrophic. Try the following code (only \"b != 0\" and \"a % b == 0\" are swapped; the rest is unchanged) for any a and for b = 0:" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "a: 17\n", "b: 0\n" ] }, { "ename": "ZeroDivisionError", "evalue": "integer division or modulo by zero", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m\n\u001b[1;31mZeroDivisionError\u001b[0m Traceback (most recent call last)", "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[0ma\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0minput\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"a: \"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 2\u001b[0m \u001b[0mb\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0minput\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"b: \"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 3\u001b[1;33m \u001b[1;32mif\u001b[0m \u001b[1;33m(\u001b[0m\u001b[0ma\u001b[0m \u001b[1;33m%\u001b[0m \u001b[0mb\u001b[0m \u001b[1;33m==\u001b[0m \u001b[1;36m0\u001b[0m \u001b[1;32mand\u001b[0m \u001b[0mb\u001b[0m \u001b[1;33m!=\u001b[0m \u001b[1;36m0\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 4\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0ma\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;34m\"is divisible by\"\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mb\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 5\u001b[0m \u001b[1;32melse\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", "\u001b[1;31mZeroDivisionError\u001b[0m: integer division or modulo by zero" ] } ], "source": [ "a = int(input(\"a: \"))\n", "b = int(input(\"b: \"))\n", "if (a % b == 0 and b != 0):\n", " print(a, \"is divisible by\", b)\n", "else:\n", " print(a, \"is NOT divisible by\", b)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "**Conclusion:** When using complex expressions, put them in the order in which they can always be executed without raising any errors! Apart from the divisibility issues like the one above, this will also come in handy with lists and similar structures.\n", "\n", "Of course, if the conditions can be run independently, always put those that compute faster first." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Scoping: how shy are the variables really?\n", "\n", "It is important to know when and where our variables live, as well as when and where can we access them.\n", "\n", "Consider the following example:" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Outside #1: 1 2 3\n", " Inside #1: 1 2 17\n", " Inside #2: 1 19 17\n", "Outside #2: 1 2 3\n", " Inside #1: 1 2 3\n", " Inside #2: 1 19 3\n", "Outside #3: 1 2 3\n" ] } ], "source": [ "x = 1\n", "y = 2\n", "def f(x, y, z=17):\n", " print(\" Inside #1:\", x, y, z)\n", " y = 19\n", " print(\" Inside #2:\", x, y, z)\n", "\n", "z = 3\n", "print(\"Outside #1:\", x, y, z)\n", "f(x, y)\n", "print(\"Outside #2:\", x, y, z)\n", "f(x, y, z)\n", "print(\"Outside #3:\", x, y, z)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "Also:" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "ename": "UnboundLocalError", "evalue": "local variable 'x' referenced before assignment", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m\n\u001b[1;31mUnboundLocalError\u001b[0m Traceback (most recent call last)", "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[0;32m 5\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mx\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 6\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 7\u001b[1;33m \u001b[0mf\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[1;32m\u001b[0m in \u001b[0;36mf\u001b[1;34m()\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[0mx\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;36m17\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 2\u001b[0m \u001b[1;32mdef\u001b[0m \u001b[0mf\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 3\u001b[1;33m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mx\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 4\u001b[0m \u001b[0mx\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;36m3\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 5\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mx\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", "\u001b[1;31mUnboundLocalError\u001b[0m: local variable 'x' referenced before assignment" ] } ], "source": [ "x = 17\n", "def f():\n", " print(x)\n", " x = 3\n", " print(x)\n", "\n", "f()" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "But:" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "17\n" ] } ], "source": [ "def f():\n", " print(x)\n", "\n", "x = 17\n", "f()" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "Obviously, some variables \"live\" inside functions, some outside of them, some everywhere,... This is called *scope*. Each programming language has its own rules of scoping. In Python, the rules are:\n", "\n", "* *Global variables* are those that belong to no function, and they exist from their first assignment until the end of program's execution or until they are manually deleted.\n", "\n", "* *Local variables* are those that belong to some function. They are created with the first assignment (including through function arguments) and they exist until the execution exits the function or until they are manually deleted. \n", "**They lose their value between two calls to the same function!**\n", "\n", "* *Static variables* exist in some languages (C/C++, for example). They belong to a function and are not seen outside of it, but they do maintain their value between the function's calls. They do not exist in Python, but it is possible to simulate a very similar behaviour." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "In Python, global variables are generally not accessible in functions. There are some exceptions to this rule:\n", "\n", "* those that are never assigned a value (like x in the previous example), and\n", "\n", "* those that are explicitly declared to be used from the global scope, using the global statement." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "So, we can fix the above example with the assignment of global variable x in function f:" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "f:\n", "17\n", "3\n", "x = 3\n" ] } ], "source": [ "x = 17\n", "def f():\n", " global x\n", " print(x)\n", " x = 3\n", " print(x)\n", "\n", "print(\"f:\")\n", "f()\n", "print(\"x =\", x)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "The variables exist from their first assignment. So, this would work as well, even though the function is *written* before the assignment (it executes after it):" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "17\n", "3\n" ] } ], "source": [ "def f():\n", " global x\n", " print(x)\n", " x = 3\n", " print(x)\n", "\n", "x = 17\n", "f()" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "### When to use global variables in functions?\n", "\n", "A short answer: never.\n", "\n", "There are examples when using global variables is justifiable, but avoid them whenever you can. A function should be an independent entity that accepts input, does some work, and outputs the result." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Lambda functions\n", "\n", "Lambda functions are a concept common to the functional programming languages, but it also exists in various forms in some other languages (MATLAB and JavaScript, for example).\n", "\n", "The main idea is to easily define an *anonymous* function (the one without a name).\n", "\n", "In Python, they are very simple: their only intent is to compute something and return it. For that reason, they do not contain more than a line of code and they don't contain return (it is implied).\n", "\n", "For example:" ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "5\n" ] } ], "source": [ "s = lambda x, y: x + y\n", "print(s(2, 3))" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "Notice how s is invoked in the same manner as the \"normal\" functions we've seen before. This is because the \"lambda\" in the name refers only to their definition, but - in the end - they *are* \"normal\" functions. For example, the one above is equivalent to this:" ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "5\n" ] } ], "source": [ "def s(x, y):\n", " return x + y\n", "print(s(2, 3))" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "Lamba functions will be more useful later on, when we cover lists. However, one can use them without lists, for example, to dynamically create a function:" ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "17 + 1 = 18\n", "17 + 7 = 24\n" ] } ], "source": [ "def mkinc(inc):\n", " return lambda x: x + inc\n", "\n", "i1 = mkinc(1)\n", "i7 = mkinc(7)\n", "print(\"17 + 1 =\", i1(17))\n", "print(\"17 + 7 =\", i7(17))" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "This example also shows that functions in Python are just a (somewhat special type of) data. We have seen this before, when we didn't call a function, but instead we printed some of the data belonging to the function max1 (its docstring):\n", "\n", "python3\n", "print(max1.__doc__)\n", "\n", "\n", "and when we gave it to another function as an argument:\n", "\n", "python3\n", "from pydoc import help\n", "help(max1)\n", "\n", "\n", "Keep in mind the following difference:\n", "\n", "* f is an object (that can be a function, as well as a \"regular\" variable);\n", "\n", "* f() is an invocation of a function f (an error occures if f is something else).\n", "\n", "This will be more important later on." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Boolean context\n", "\n", "If a function is defined, its Boolean interpretation is True:" ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n" ] } ], "source": [ "def f(x):\n", " print(\"X\")\n", "\n", "print(bool(f))" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "For that reason, be careful to always call it properly, with parentheses:" ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "f evaluates to True\n", "f() evaluates to False\n" ] } ], "source": [ "def f():\n", " return False\n", "\n", "if f:\n", " print(\"f evaluates to True\")\n", "else:\n", " print(\"f evaluates to False\")\n", "\n", "if f():\n", " print(\"f() evaluates to True\")\n", "else:\n", " print(\"f() evaluates to False\")" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## What more can be done?\n", "\n", "* Functions defined inside other functions -- while it has its organizational uses, it is generally not that useful and will not be covered here;\n", "\n", "* Recursions: functions that call themselves." ] } ], "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.6.3" } }, "nbformat": 4, "nbformat_minor": 1 }