{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## Functions" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A function in Python is defined using the keyword `def`, followed by a function name, a signature within parentheses `()`, and a colon `:`. The following code, with one additional level of indentation, is the function body." ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "collapsed": false }, "outputs": [], "source": [ "def func0(): \n", " print(\"test\")" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "test\n" ] } ], "source": [ "func0()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Optionally, but highly recommended, we can define a so called \"docstring\", which is a description of the functions purpose and behaivor. The docstring should follow directly after the function definition, before the code in the function body." ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "collapsed": false }, "outputs": [], "source": [ "def func1(s):\n", " \"\"\"\n", " Print a string 's' and tell how many characters it has \n", " \"\"\"\n", " \n", " print(s + \" has \" + str(len(s)) + \" characters\")" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on function func1 in module __main__:\n", "\n", "func1(s)\n", " Print a string 's' and tell how many characters it has\n", "\n" ] } ], "source": [ "help(func1)" ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "test has 4 characters\n" ] } ], "source": [ "func1(\"test\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Functions that returns a value use the `return` keyword:" ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "collapsed": false }, "outputs": [], "source": [ "def square(x):\n", " \"\"\"\n", " Return the square of x.\n", " \"\"\"\n", " return x ** 2" ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "16" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "y = square(4); y" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can return multiple values from a function using tuples (see above):" ] }, { "cell_type": "code", "execution_count": 15, "metadata": { "collapsed": false }, "outputs": [], "source": [ "def powers(x):\n", " \"\"\"\n", " Return a few powers of x.\n", " \"\"\"\n", " return x ** 2, x ** 3, x ** 4" ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "(9, 27, 81)" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "powers(3)" ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "81\n" ] } ], "source": [ "x2, x3, x4 = powers(3)\n", "\n", "print(x4)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Default argument and keyword arguments" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In a definition of a function, we can give default values to the arguments the function takes:" ] }, { "cell_type": "code", "execution_count": 25, "metadata": { "collapsed": false }, "outputs": [], "source": [ "def myfunc(x, p=2, bug=False):\n", " if bug:\n", " print(\"evaluating myfunc for x = \" + str(x) + \" using exponent p = \" + str(p))\n", " return x**p" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If we don't provide a value of the `debug` argument when calling the the function `myfunc` it defaults to the value provided in the function definition:" ] }, { "cell_type": "code", "execution_count": 26, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "125" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "myfunc(5,p=3)" ] }, { "cell_type": "code", "execution_count": 29, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "evaluating myfunc for x = 5 using exponent p = 2\n" ] }, { "data": { "text/plain": [ "25" ] }, "execution_count": 29, "metadata": {}, "output_type": "execute_result" } ], "source": [ "myfunc(5, bug=True)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If we explicitly list the name of the arguments in the function calls, they do not need to come in the same order as in the function definition. This is called *keyword* arguments, and is often very useful in functions that takes a lot of optional arguments." ] }, { "cell_type": "code", "execution_count": 24, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "evaluating myfunc for x = 7 using exponent p = 3\n" ] }, { "data": { "text/plain": [ "343" ] }, "execution_count": 24, "metadata": {}, "output_type": "execute_result" } ], "source": [ "myfunc(p=3, debug=True, x=7)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Anonymous/unnamed functions (lambda function)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In Python we can also create unnamed functions, using the `lambda` keyword:" ] }, { "cell_type": "code", "execution_count": 30, "metadata": { "collapsed": false }, "outputs": [], "source": [ "f1 = lambda x: x**2\n", " \n", "# is equivalent to \n", "\n", "def f2(x):\n", " return x**2" ] }, { "cell_type": "code", "execution_count": 31, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "(4, 4)" ] }, "execution_count": 31, "metadata": {}, "output_type": "execute_result" } ], "source": [ "f1(2), f2(2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This technique is useful for example when we want to pass a simple function as an argument to another function, like this:" ] }, { "cell_type": "code", "execution_count": 33, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "" ] }, "execution_count": 33, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# map is a built-in python function\n", "map(lambda x: x**2, range(-3,4))" ] }, { "cell_type": "code", "execution_count": 36, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "[9, 4, 1, 0, 1, 4, 9]" ] }, "execution_count": 36, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# in python 3 we can use `list(...)` to convert the iterator to an explicit list\n", "list(map(f2, range(-3,4)))" ] }, { "cell_type": "code", "execution_count": 40, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[(11, -3), (3, 1), (1, 2), (5, 10)]" ] }, "execution_count": 40, "metadata": {}, "output_type": "execute_result" } ], "source": [ "def key(x):\n", " return x[1]\n", "\n", "a = [(1, 2), (3, 1), (5, 10), (11, -3)]\n", "a.sort(key=key)\n", "a" ] }, { "cell_type": "code", "execution_count": 39, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[(11, -3), (3, 1), (1, 2), (5, 10)]" ] }, "execution_count": 39, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = [(1, 2), (3, 1), (5, 10), (11, -3)]\n", "a.sort(key=lambda x: x[1])\n", "a" ] } ], "metadata": { "gist_info": { "gist_id": null, "gist_url": null }, "kernelspec": { "display_name": "Py3 pangeo", "language": "python", "name": "pangeo" }, "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.5" } }, "nbformat": 4, "nbformat_minor": 2 }