{ "metadata": { "name": "", "signature": "sha256:d47dc1958002c44d6bc6ec528a30c463a3c439b1858eb239d6783adce907e061" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "heading", "level": 1, "metadata": {}, "source": [ "Functions" ] }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Syntax" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "skip" } }, "source": [ "You now know how to run Python code, assign variables, and write control flow statements, which allows us to write programs that can do calculations. In fact, this is all you *really* need to write programs (except for being able to read in and write out data which we will talk about later). However, with only this, programs will quickly become very long and unreadable. So one very important rule in programming is to **avoid repetition**." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "The syntax for a **function** is:\n", " \n", " def function_name(arguments):\n", " # code here\n", " return values" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Functions are the **building blocks** of programs - think of them as basic units that are given a certain input an accomplish a certain task. Over time, you can build up more complex programs while preserving readability." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Similarly to ``if`` statements and ``for`` and ``while`` loops, indentation is very important because it shows where the function starts and ends.\n", "\n", "**Note**: it is a common convention to always use lowercase names for functions." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "A function can take multiple arguments..." ] }, { "cell_type": "code", "collapsed": false, "input": [ "def add(a, b):\n", " return a + b\n", "\n", "print(add(1,3))\n", "print(add(1.,3.2))\n", "print(add(4,3.))" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "... and can also return multiple values:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "def double_and_halve(value):\n", " return value * 2., value / 2.\n", "\n", "print(double_and_halve(5.))" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "If multiple values are returned, you can store them in separate variables." ] }, { "cell_type": "code", "collapsed": false, "input": [ "d, h = double_and_halve(5.)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "print(d)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "print(h)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Functions can call other functions:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "def do_a():\n", " print(\"doing A\")\n", " \n", "def do_b():\n", " print(\"doing B\")\n", " \n", "def do_a_and_b():\n", " do_a()\n", " do_b()" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "do_a_and_b()" ], "language": "python", "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "**Figuring out the right functions is half the trick behind a good program**. A good function has a clear purpose that can, ideally, be described in one sentence of natural language.\n", "\n", "Beginners typically err on the side of defining too few functions and writing monsters spanning a couple of screen pages. That's a clear indication that you're doing it wrong. A good function can be taken in (albeit perhaps not understood) at a clance." ] }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Exercise 1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Copy your code that finds prime numbers here and modify it so as to make it a function that given a number will return ``True`` or ``False`` depending on whether it is prime." ] }, { "cell_type": "code", "collapsed": false, "input": [ "\n", "# your solution here\n" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Exercise 2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Try and write a function that will return the factorial of a number (e.g. ``5!=5*4*3*2*1``). First you can try and write a function that uses a loop internally.\n", "\n", "It is possible for functions to call themselves (**recursive** functions), so see if you can write a function that uses **no** loops!" ] }, { "cell_type": "code", "collapsed": false, "input": [ "\n", "# enter your solution here\n" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Optional Arguments" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In addition to normal arguments, functions can take **optional** arguments that can default to a certain value. For example, in the following case:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "def say_hello(first_name, middle_name='', last_name=''):\n", " print(\"First name: \" + first_name)\n", " if middle_name != '':\n", " print(\"Middle name: \" + middle_name)\n", " if last_name != '':\n", " print(\"Last name: \" + last_name)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "we can call the function either with one argument:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "say_hello(\"Michael\")" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and we can also give one or both optional arguments (and the optional arguments can be given in any order):" ] }, { "cell_type": "code", "collapsed": false, "input": [ "say_hello(\"Michael\", last_name=\"Palin\")" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "say_hello(\"Michael\", middle_name=\"Edward\", last_name=\"Palin\")" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "say_hello(\"Michael\", last_name=\"Palin\", middle_name=\"Edward\")" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Built-in functions" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Some of you may have already noticed that there are a few functions that are defined by default in Python:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "x = [1,3,6,8,3]" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "len(x)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "sum(x)" ], "language": "python", "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "int(1.2)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "A [full list of built-in functions](http://docs.python.org/3/library/functions.html) is available from http://docs.python.org. Note that there are not *that* many - these are only the most common functions. Most functions are in fact kept inside **modules**, which we will cover later." ] }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Exercise 3" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Write a function that takes a list, and returns the mean of the values. Test it with the following list:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "l = [1, 3, 4, 5, 6, 7]\n", "\n", "# enter your solution here" ], "language": "python", "metadata": {}, "outputs": [] } ], "metadata": {} } ] }