{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "(functions_python)=\n", "# Creating custom functions\n", "``` {index} Creating functions (python)\n", "```\n", "Functions in Python are blocks of code that will only be executed when called. They look like this:\n", "\n", "```python\n", " def function_name(arg1, arg2, ...):\n", " # some code to execute\n", " return # return some variables, optional\n", "```\n", "\n", "Function names should be descriptive. The arguments are separated by commas and will become local variables within the function. Any object, and any number of objects, can be returned from a function.\n", "\n", "Functions have to appear in the code before you execute them:" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1 - 2 = -1\n", "17 - 5 = 12\n", "9 - 28 = -19\n" ] } ], "source": [ "a = 1\n", "b = 2\n", "\n", "# Create a function\n", "def subtract_numbers(a, b):\n", " return f\"{a} - {b} = {a-b}\"\n", "\n", "# Call the function\n", "print(subtract_numbers(a, b))\n", "print(subtract_numbers(17,5))\n", "print(subtract_numbers(9, 28))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Even though we have variables `a` and `b` in the code, the function does not use them unless they are arguments to the function. Variables `a` and `b` inside the function are local variables and they only exist there. If we want to use global variables (variables outside of the function), the code will look like this:" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "a = 12\n", "a = 16\n" ] } ], "source": [ "a = 10\n", "\n", "# Create a function\n", "\n", "def add_to_variable_a(b):\n", " global a # Make 'a' a global variable\n", " a += b\n", " return a\n", "\n", "# Call the function\n", "\n", "print(\"a =\", add_to_variable_a(2))\n", "print(\"a =\", add_to_variable_a(4))\n", "\n", "# Note how variable a changed" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "(functions_exercises)=\n", "## Exercises\n", "-------\n", "* **Immutable vs Mutable** Functions can change the objects (variables) passed to them. Everything depends if an object is mutable. Compare the behaviour of the two functions below, where the one which changes the list is an example of an [*in-place algorithm*](https://en.wikipedia.org/wiki/In-place_algorithm):" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Original list: [1, 2, 3]\n", "double_list1: [1, 2, 3]\n", "double_list2: [2, 4, 6]\n" ] } ], "source": [ "def double_list1(l):\n", " for element in l:\n", " element *= 2\n", "\n", "def double_list2(l):\n", " for i in range(len(l)):\n", " l[i] *= 2\n", "\n", " \n", "l = [1,2,3]\n", "print(\"Original list:\", l)\n", "\n", "double_list1(l)\n", "print(\"double_list1:\", l)\n", "\n", "double_list2(l)\n", "print(\"double_list2:\", l)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let us have some fun with mutability. Define a function which takes a list and doubles the elements at the even indices and negates the ones at odd indices. Test it with your input.\n", "\n", "**HINT** use the `for i in range(len(l)):` structure of the for loop, a different one might not mutate the list." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "````{admonition} Answer\n", ":class: dropdown\n", " \n", "```python \n", "def funnyFunc(l):\n", " for i in range(len(l)):\n", "\n", " if i%2==0:\n", " l[i]*=2\n", " else:\n", " l[i]*=(-1)\n", "\n", " return l\n", "\n", "\n", "print(funnyFunc([1,2,3,4,7,4,3]))\n", "```\n", "\n", "````" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "----------\n", "* **Simple Search** Define a function which checks if an element is present in a list and return a boolean value depending on the result. The signature should be `def simpleSearch(l, a):`." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "````{admonition} Answer\n", ":class: dropdown\n", "\n", "```python\n", "def simpleSearch(l,a):\n", " for i in l:\n", " if a == i:\n", " return True\n", "\n", " return False\n", "\n", "\n", "print(simpleSearch([1,2,3],5))\n", "print(simpleSearch([\"Boo\", \"Foo\"], \"Moo\"))\n", "print(simpleSearch([True, True],False))\n", "print(simpleSearch([1.,1.],1))\n", "```\n", "\n", "````" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---------------\n", "* **Ah..Interns**: Of course Professor Earth agreed to employ Jenny for the summer internship about temperature analysis. Unfortunately she made a little mistake and now the machine reads the digits of each number in the reverse order. \n", "\n", "```python\n", " temp = ['009','679','568','444']\n", "```\n", " \n", "Jenny produced so many measurements that she would not be able to change them manually. You have to help her! In addition she needs to provide a function `avgList(l)` which will compute the average of temperature reads from a transformed list. Jenny needs you! " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "````{admonition} Answer\n", ":class: dropdown\n", "\n", "```python\n", "def revNums(l):\n", " for i in range(len(l)):\n", " l[i] = int(l[i][::-1])\n", "\n", " return l\n", "\n", "\n", "def avgList(l):\n", " return sum(l)/len(l)\n", "\n", "\n", "temp = ['009','679','568','444']\n", "\n", "print(revNums(temp))\n", "print(avgList(temp))\n", "```\n", " \n", "````" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "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.7.3" } }, "nbformat": 4, "nbformat_minor": 4 }