{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "### 4. Functions and Methods\n", "\n", "After today's lesson, you'll know how to write Python functions in a more structured way, which will allow you to undertake bigger projects while keeping your code readable and maintainable.\n", "\n", "#### Functions\n", "\n", "A function in programming is basically the same as the functions you've encountered and worked with in maths. You give it arguments and it returns something. An example in Python is as follows:" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def f(x):\n", " return x**2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This is equivalent to \n", "\n", "$$ f(x) = x^2 $$\n", "\n", "To define a function in Python, you need to follow the following syntax:\n", " \n", " def function_name(argument):\n", " statements\n", "\n", "We can get the value of a function for a certain argument as in the following example:" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "25.0\n" ] } ], "source": [ "y = f(5.0)\n", "print(y)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can see that in the above example, `y` was assigned to be `f(5.0)`. This returned the value `5**2`, resulting in `y = 25`.\n", "\n", "Functions can take any type of argument, not just numbers, but we must take care that we pass the right types of arguments to functions because else we'll get errors, as shown in the cell below:" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": false }, "outputs": [ { "ename": "TypeError", "evalue": "unsupported operand type(s) for ** or pow(): 'str' and 'int'", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0my\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mf\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"A string\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;32m\u001b[0m in \u001b[0;36mf\u001b[0;34m(x)\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mf\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mx\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0mx\u001b[0m\u001b[0;34m**\u001b[0m\u001b[0;36m2\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mTypeError\u001b[0m: unsupported operand type(s) for ** or pow(): 'str' and 'int'" ] } ], "source": [ "y = f(\"A string\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "For functions with many arguments, we can name the arguments. This allows for more legible code:\n", " \n", " y = function_name(argument_1 = 1,\n", " argument_2 = 2,\n", " argument_3 = 3)\n", "\n", "Using functions, we can eliminate a lot of copy/pasting allowing for short and sweet code.\n", "\n", "An example is shown below, where we have rewritten the factorial program so that we can use it elsewhere." ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3628800\n" ] } ], "source": [ "def factorial(n):\n", " # input integer n\n", " # Is n = 0 or 1?\n", " if n == 0 or n ==1:\n", " # Yes it is, so factorial = 1\n", " factorial = 1\n", " else:\n", " # Start with factorial = n\n", " factorial = n\n", " while n != 1:\n", " # Decrease n by 1\n", " n -= 1\n", " # Multiply factorial by n\n", " factorial = factorial * n\n", " # If n is not 1, then this loop will continue\n", " return factorial\n", "\n", "print(factorial(10))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Methods\n", "\n", "Methods are functions that belong to objects. They will sometimes return a value, although often not.\n", "\n", "We'll look at lists as an example as there are a number of useful methods that you can use on them. They are used in the following way:" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['zero', 'one', 'two', 'three', 'four', 'five']\n" ] } ], "source": [ "list1 = [\"zero\", \"one\", \"two\", \"three\", \"four\"]\n", "list1.append(\"five\") #This method appends the string \"five\" to the end of the list.\n", "print(list1)" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['one', 'two', 'three', 'four', 'five']\n" ] } ], "source": [ "list1.pop(0) #Removes element at index 0\n", "print(list1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The way you use a method is the following:\n", " \n", " object.method_name(parameters)\n", " \n", "A list of some useful methods for lists is as follows:\n", "\n", " list.append(x): Add x to the end of the list\n", " list.extend(list2): Join list2 with list\n", " list.insert(i,x): Insert x at index i\n", " list.pop(i): Remove item at index i (also returns the removed element)\n", " list.index(x): Returns the index of the first item whose value is x\n", " list.count(x): Returns the number of instances of x in the list\n", " \n", "There are many more, but that should cover a substantial number of use cases. \n", "\n", "Making methods requires further knowledge on objects, and will be introduced next year, but knowing about them and being able to use them is vital to programming in Python." ] } ], "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.5.1" } }, "nbformat": 4, "nbformat_minor": 0 }