{ "metadata": { "name": "", "signature": "sha256:8aef276f358fdebd3620d908404f708cddf4ffbd66a4034a239ae76711c700e7" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "[![Py4Life](https://raw.githubusercontent.com/Py4Life/TAU2015/gh-pages/img/Py4Life-logo-small.png)](http://py4life.github.io/TAU2015/)\n", "## Lecture 3 - 25.3.2015\n", "### Last update: 22.3.2015\n", "### Tel-Aviv University / 0411-3122 / Spring 2015" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Previously on Py4Life\n", "\n", "- Python\n", "- Variables\n", "- Operators\n", "- strings\n", "- lists\n", "- Flow control: conditions (if,elif,else) and loops (for,while)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## In today's episode\n", "- Dictionaries\n", "- Functions\n", "- Arguments\n", "- Scopes" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Dictionaries\n", "### Reminder - Lists\n", "Lists are a data structure used to store collections of elements (int, float, str etc.) in an __ordered__ way." ] }, { "cell_type": "code", "collapsed": false, "input": [ "organisms = ['Pan troglodytes', 'Gallus gallus', 'Xenopus laevis', 'Vipera palaestinae']" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 6 }, { "cell_type": "markdown", "metadata": {}, "source": [ "We access elements of lists by using their _index_:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "print(organisms[0])\n", "print(organisms[2])" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Pan troglodytes\n", "Xenopus laevis\n" ] } ], "prompt_number": 2 }, { "cell_type": "markdown", "metadata": {}, "source": [ "__Dictionaries__ are another data structure used to store collections of elements, only this time they can be accessed through a _key_. Keys can be anything - a string, an integer, float and so on. Each key is connected to a _value_." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Defining dictionaries:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "organisms_classes = {'Pan troglodytes': 'Mammalia', 'Gallus gallus': 'Aves', 'Xenopus laevis': 'Amphibia', 'Vipera palaestinae': 'Reptilia'}" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 1 }, { "cell_type": "markdown", "metadata": {}, "source": [ "In this dictionary, the _keys_ are the organisms and the _values_ are the class of each organism. Both are of type `str`." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Another example would be a dictionary representing the number of observations of various species:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "observations = {'Equus zebra': 143,\n", " 'Hippopotamus amphibius': 27,\n", " 'Giraffa camelopardalis': 71,\n", " 'Panthera leo': 112}" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 9 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here, the keys are of type `str` and the values are of type `int`. Any other combination could be used.\n", "![safari](https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcTL-7qevLJk3T6miuV7zzlxGqH0WFyEv8ejFqw7444QMEElRvkblg)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Accessing dictionary records\n", "Accessing a dictionary record is similar to what we did with lists, only this time we'll call a _key_ instead of an _index_:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "print(organisms_classes['Pan troglodytes'])\n", "print(organisms_classes['Gallus gallus'])" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Mammalia\n", "Aves\n" ] } ], "prompt_number": 2 }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Changing and adding records\n", "We can change the dictionary by simply assigning a new value to a key." ] }, { "cell_type": "code", "collapsed": false, "input": [ "organisms_classes['Pan troglodytes'] = 'Mammals'\n", "print(organisms_classes['Pan troglodytes'])" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Mammals\n" ] } ], "prompt_number": 3 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Similarly, we can use this syntax to add new records: " ] }, { "cell_type": "code", "collapsed": false, "input": [ "organisms_classes['Danio rerio'] = 'Actinopterygii'\n", "print(organisms_classes['Danio rerio'])" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Actinopterygii\n" ] } ], "prompt_number": 4 }, { "cell_type": "markdown", "metadata": {}, "source": [ "__Note__: A dictionary may not contain multiple records with the same _key_, but it may contain many keys with the same _value_." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Looping throgh dictionaries\n", "Remember the __for__ loop and how we used it to loop on lists?" ] }, { "cell_type": "code", "collapsed": false, "input": [ "for organism in organisms:\n", " print(organism)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Pan troglodytes\n", "Gallus gallus\n", "Xenopus laevis\n", "Vipera palaestinae\n" ] } ], "prompt_number": 7 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Well, it also works on dictionaries! The for loop simply itterates over the _keys_ of the dictionary." ] }, { "cell_type": "code", "collapsed": false, "input": [ "for organism in organisms_classes:\n", " print(organism, 'belongs to the', organisms_classes[organism], 'class.')" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Pan troglodytes belongs to the Mammals class.\n", "Gallus gallus belongs to the Aves class.\n", "Vipera palaestinae belongs to the Reptilia class.\n", "Danio rerio belongs to the Actinopterygii class.\n", "Xenopus laevis belongs to the Amphibia class.\n" ] } ], "prompt_number": 8 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Notice that dictionary items don't keep their original order." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can even change values while looping:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "for animal in observations:\n", " if observations[animal] > 50:\n", " observations[animal] = True\n", " else:\n", " observations[animal] = False\n", "print(observations)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "{'Giraffa camelopardalis': True, 'Equus zebra': True, 'Panthera leo': True, 'Hippopotamus amphibius': False}\n" ] } ], "prompt_number": 10 }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Is it in the dictionary?\n", "We can check if a __key__ is in the dictionary using an _if_ statement:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "'Vipera palaestinae' in organisms_classes" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 11, "text": [ "True" ] } ], "prompt_number": 11 }, { "cell_type": "code", "collapsed": false, "input": [ "'Bos taurus' in organisms_classes" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 12, "text": [ "False" ] } ], "prompt_number": 12 }, { "cell_type": "code", "collapsed": false, "input": [ "new_organism = ['Vipera palaestinae', 'Bos taurus']\n", "for organism in new_organism:\n", " if organism in organisms_classes:\n", " print(organism, 'belongs to the', organisms_classes[organism], 'class.')\n", " else:\n", " print(organism, 'not found in dictionary.')" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Vipera palaestinae belongs to the Reptilia class.\n", "Bos taurus not found in dictionary.\n" ] } ], "prompt_number": 10 }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Class exercise 3A" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "1) Create a dictionary with the keys 'Name','Address' and 'Phone', insert your details as values, and use the dictionary to print a sentence such as \"My name is James Watson, I live in Cambridge and my phone number is 12345678\"" ] }, { "cell_type": "code", "collapsed": false, "input": [ "# Create dictionary\n", "details_dict = {'Name': 'James Watson', 'Address': 'Cambridge', 'Phone': '12345678'}\n", "\n", "# print sentence\n", "print(\"My name is\",details_dict['Name'],\"I live in\",details_dict['Address'],\"My phone number is\",details_dict['Phone'])" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "2) Given in the code below is a dictionary (named codon_table) where the keys represent codons and the values are the corresponding amino acids. Use the dictionary to translate the codons in the list (named seq_list) and print out the resulting sequence of amino acids.\n", "* Hint: to print without creating a newline, use `print(\"your print\", end='')`" ] }, { "cell_type": "code", "collapsed": false, "input": [ "# Create codons dictionary\n", "bases = ['t', 'c', 'a', 'g']\n", "codons = [a+b+c for a in bases for b in bases for c in bases]\n", "amino_acids = 'FFLLSSSSYY**CC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG'\n", "codon_table = dict(zip(codons, amino_acids))\n", "\n", "# Sequence list\n", "seq_list = [\"atg\",\"caa\",\"ggc\",\"ata\",\"tca\",\"tgg\",\"cga\",\"agg\",\"cct\",\"taa\"]\n", "\n", "# iterate on list and translate\n", "for codon in seq_list:\n", " print(codon_table[codon], end='')" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "MQGISWRRP*" ] } ], "prompt_number": 2 }, { "cell_type": "markdown", "metadata": {}, "source": [ "## What's a function?\n", "### In mathematics:\n", "A function is like a _machine_, that (usually) takes a number, performs some mathematical process and returns another number. \n", "For example, the function $f(x) = 2x + 6$ \n", "When the function takes 3 (that is, x = 3), it returns 2*3 + 6 = 12 \n", "And in 'pythonic':" ] }, { "cell_type": "code", "collapsed": false, "input": [ "x = 3\n", "y = 2*x + 6\n", "print(y)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "12\n" ] } ], "prompt_number": 2 }, { "cell_type": "markdown", "metadata": {}, "source": [ "### In computer science\n", "A function is a piece of code that performs some process. Like the mathematical concept, a function receives _inputs_ and returns _outputs_. \n", "We _define_ functions with the __def__ command. \n", "The general syntax is: " ] }, { "cell_type": "code", "collapsed": false, "input": [ "def function_name(input1, input2, input3,...):\n", " # some processes\n", " .\n", " .\n", " .\n", " return output" ], "language": "python", "metadata": {}, "outputs": [ { "ename": "SyntaxError", "evalue": "invalid syntax (, line 1)", "output_type": "pyerr", "traceback": [ "\u001b[1;36m File \u001b[1;32m\"\"\u001b[1;36m, line \u001b[1;32m1\u001b[0m\n\u001b[1;33m def function_name(input1, input2, input3,...):\u001b[0m\n\u001b[1;37m ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m invalid syntax\n" ] } ], "prompt_number": 3 }, { "cell_type": "code", "collapsed": false, "input": [ "def linear1 (x):\n", " y = 2*x + 6\n", " return y" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 4 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Once a function is defined, we can call it whenever we need it (i.e. multiple times), with different inputs." ] }, { "cell_type": "code", "collapsed": false, "input": [ "result1 = linear1(3)\n", "print(result1)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "12\n" ] } ], "prompt_number": 5 }, { "cell_type": "code", "collapsed": false, "input": [ "result2 = linear1(7)\n", "print(result2)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "20\n" ] } ], "prompt_number": 6 }, { "cell_type": "markdown", "metadata": {}, "source": [ "A function may have more than one input, and they can also be other types of variables. \n", "For example, the following function receives a __list__ of sequences and concatenates a given sequence __string__ to each sequence in the list. It then returns the new list." ] }, { "cell_type": "code", "collapsed": false, "input": [ "def concat_to_sequences(sequence_list, sequence_to_concat):\n", " new_list = []\n", " for seq in sequence_list:\n", " new_list.append(seq + sequence_to_concat)\n", " return new_list" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 11 }, { "cell_type": "code", "collapsed": false, "input": [ "my_sequences = ['AGTTAGAGTTA', 'TTACCAGTG', 'GGCAACTTTAGG']\n", "new_sequences = concat_to_sequences(my_sequences, 'GGG')\n", "print(my_sequences)\n", "print(new_sequences)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "['AGTTAGAGTTA', 'TTACCAGTG', 'GGCAACTTTAGG']\n", "['AGTTAGAGTTAGGG', 'TTACCAGTGGGG', 'GGCAACTTTAGGGGG']\n" ] } ], "prompt_number": 12 }, { "cell_type": "markdown", "metadata": {}, "source": [ "The inputs of a function are also called __Arguments__ or formal variables." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Why do we need functions?\n", "So why bother? Can't we just write code as we did so far and avoid all that functions mess? \n", "Functions are good for (at least) three reasons:\n", "* Prevent code duplication - if we perform the same process multiple times, we don't have to write it again every time. We just call the function, thereby making the code shorter and more readable and avoid errors.\n", "* Modularity - Your code can easily be separated to small components, which can be reused and recombined.\n", "* Abstraction - separating a complex task into smaller and more simple tasks." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### A biological example" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now, let's use some of the stuff we've learned to write a function that finds the reverse complement of a given sequence. Let's start by finding the complement." ] }, { "cell_type": "code", "collapsed": false, "input": [ "def complement(sequence):\n", " transcript_dict = {'A': 'T', 'T': 'A', 'G': 'C', 'C': 'G'}\n", " complement = ''\n", " for base in sequence:\n", " complement += transcript_dict[base]\n", " return complement" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 2 }, { "cell_type": "code", "collapsed": false, "input": [ "my_dna = 'ACGCTATTAGAGGGCGAGAAGCTAGAGGA'\n", "my_complement = complement(my_dna)\n", "print(my_complement)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "TGCGATAATCTCCCGCTCTTCGATCTCCT\n" ] } ], "prompt_number": 6 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now, let's write another function, that reverses a given sequences." ] }, { "cell_type": "code", "collapsed": false, "input": [ "def reverse_sequence(sequence):\n", " reversed_seq = ''\n", " seq_as_list = list(sequence)\n", " for base in reversed(seq_as_list):\n", " reversed_seq += base\n", " return reversed_seq" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 3 }, { "cell_type": "code", "collapsed": false, "input": [ "my_reverse_complement = reverse_sequence(my_complement)\n", "print(my_reverse_complement)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "TCCTCTAGCTTCTCGCCCTCTAATAGCGT\n" ] } ], "prompt_number": 26 }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can call functions _from within_ a function, thereby wrapping the two functions we have in a third function." ] }, { "cell_type": "code", "collapsed": false, "input": [ "def reverse_complement(sequence):\n", " complement_seq = complement(sequence)\n", " reverse_complement = reverse_sequence(complement_seq)\n", " return reverse_complement" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 10 }, { "cell_type": "code", "collapsed": false, "input": [ "print(reverse_complement(my_dna))" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "TCCTCTAGCTTCTCGCCCTCTAATAGCGT\n" ] } ], "prompt_number": 29 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Fuctions don't __have__ to return anything. Sometimes they just print stuff to the screen or to a file (next lesson). For example, we can take the function we created above and simply replace 'return' with 'print':" ] }, { "cell_type": "code", "collapsed": false, "input": [ "def print_reverse_complement(sequence):\n", " complement_seq = complement(sequence)\n", " reverse_complement = reverse_sequence(complement_seq)\n", " print(reverse_complement)" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 8 }, { "cell_type": "code", "collapsed": false, "input": [ "print_reverse_complement(my_dna)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "TCCTCTAGCTTCTCGCCCTCTAATAGCGT\n" ] } ], "prompt_number": 9 }, { "cell_type": "markdown", "metadata": {}, "source": [ "So, what's the difference between __return__ and __print__??? \n", "As the names suggest, while __print__ just prints the output of the function, __return__ retrns a value that can be stored within a variable. The difference is especially noticable when the output is not a string (e.g. list, dictionary etc). Even if the output is a string, __retun__ let's you further manipulate the output, while __print__ does not. " ] }, { "cell_type": "code", "collapsed": false, "input": [ "my_reverse_complement = reverse_complement(my_dna)\n", "final_sequence = \"ATG\" + my_reverse_complement + \"TAA\"\n", "print(final_sequence)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "ATGTCCTCTAGCTTCTCGCCCTCTAATAGCGTTAA\n" ] } ], "prompt_number": 11 }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Documenting your functions\n", "It is considered good practice to add documentation to functions you write - what do they do, what's their input and output etc. It becomes very useful once you have lots of code that you want to reuse. If you document your functions, you won't have to read the whole code when you need them again. \n", "Documenting functions is done by adding a '_docstring_' right under the definition line. It is enclosed by \"\"\". For example:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "def reverse_complement(sequence):\n", " \"\"\"\n", " Receives a string of DNA sequence and returns a string of it's reverse complement\n", " \"\"\"\n", " complement_seq = complement(sequence)\n", " reverse_complement = reverse_sequence(complement_seq)\n", " return reverse_complement" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 1 }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can easily access the documentation of a function using the `help()` command." ] }, { "cell_type": "code", "collapsed": false, "input": [ "help(reverse_complement)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Help on function reverse_complement in module __main__:\n", "\n", "reverse_complement(sequence)\n", " Receives a string of DNA sequence and returns a string of it's reverse complement\n", "\n" ] } ], "prompt_number": 2 }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Class exercise 3B" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "1) Define a function that receives two sequences strings and __returns__ (not just prints) the first five bases of the longer sequence. Test your function on the given sequences. Document your function.\n", "* Hint: recall the _len()_ function and string slicing." ] }, { "cell_type": "code", "collapsed": false, "input": [ "# define function\n", "def first_5_longer_sequence(seq1,seq2):\n", " if len(seq1) > len(seq2):\n", " return seq1[:5]\n", " else:\n", " return seq2[:5]\n", " \n", "# Test function\n", "sequence1 = \"aggtctcggatataggcgcgatattta\"\n", "sequence2 = \"ttaagccacgcttcggatta\"\n", "first_5 = first_5_longer_sequence(sequence1, sequence2)\n", "print(first_5)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "2) Define a function that receives a sequence string and __returns__ a __list__ of the 1st, 3rd, 5th, 7th bases etc. Test your function on the given sequence." ] }, { "cell_type": "code", "collapsed": false, "input": [ "# define function\n", "def odd_bases(seq):\n", " odd_bases_list = []\n", " for i in range(len(seq)):\n", " if i % 2 == 0:\n", " odd_bases_list.append(seq[i]) \n", " return odd_bases_list\n", "\n", "# or another option\n", "def odd_bases(seq):\n", " odd_bases_list = list(seq[::2]) \n", " return odd_bases_list\n", "\n", "# Test function\n", "odd_bases_list = odd_bases(\"aggtctcggatataggcgcgatattta\")\n", "print(odd_bases_list)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Built-in functions" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In fact, we've used functions before, without defining them first. For example: print(), type(), int(), len() etc. These functions are provided by the courtesy of Python developers. It is strongly adviced not to overwrite built-in functions with your own functions. That is, don't do:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "def len(lst):\n", " .\n", " .\n", " ." ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "just use another name... \n", "We can acquire more functions written by others by __importing__ them into our code. We'll do that on the next lesson." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Scopes" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Assume we have the following function, that calculates the hypotenuse (\u05d9\u05ea\u05e8) given two sides of a right triangle. (Remember Pythagoras' theorem?)" ] }, { "cell_type": "code", "collapsed": false, "input": [ "def pythagoras(a,b):\n", " hypo_square = a**2 + b**2\n", " hypo = hypo_square**0.5" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 13 }, { "cell_type": "markdown", "metadata": {}, "source": [ "And now we want to run our function on the sides _a_ = 3 and _b_ = 5. So we do:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "pythagoras(3,5)\n", "print(hypo)" ], "language": "python", "metadata": {}, "outputs": [ { "ename": "NameError", "evalue": "name 'hypo' is not defined", "output_type": "pyerr", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m\n\u001b[1;31mNameError\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[0mpythagoras\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m3\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;36m5\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 2\u001b[1;33m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mhypo\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[1;31mNameError\u001b[0m: name 'hypo' is not defined" ] } ], "prompt_number": 14 }, { "cell_type": "markdown", "metadata": {}, "source": [ "__What happened to our result???__ \n", "The answer is _Scope_! \n", "The variable _hypo_ 'lives' only as long as the function is running. In other words, it exists only withing the _scope_ of the function, and so do _a, b_ and _hypo_square_! \n", "If we try to print hypo from _within_ the function:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "def pythagoras(a,b):\n", " hypo_square = a**2 + b**2\n", " hypo = hypo_square**0.5\n", " print(hypo)\n", "pythagoras(3,5)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "5.830951894845301\n" ] } ], "prompt_number": 15 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Or even better, we can use the __return__ statement to get the result. Like this:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "def pythagoras(a,b):\n", " hypo_square = a**2 + b**2\n", " hypo = hypo_square**0.5\n", " return(hypo)\n", "\n", "result = pythagoras(3,5)\n", "print(result)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "5.830951894845301\n" ] } ], "prompt_number": 16 }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Fin\n", "This notebook is part of the _Python Programming for Life Sciences Graduate Students_ course given in Tel-Aviv University, Spring 2015.\n", "\n", "The notebook was written using [Python](http://pytho.org/) 3.4.1 and [IPython](http://ipython.org/) 2.1.0 (download from [PyZo](http://www.pyzo.org/downloads.html)).\n", "\n", "The code is available at https://github.com//Py4Life/TAU2015/blob/master/lecture3.ipynb.\n", "\n", "The notebook can be viewed online at http://nbviewer.ipython.org//Py4Life/TAU2015/Py4Life/blob/master/lecture3.ipynb.\n", "\n", "The notebook is also available as a PDF at https://github.com//Py4Life/TAU2015/blob/master/lecture3.pdf?raw=true.\n", "\n", "This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.\n", "\n", "![Python logo](https://www.python.org/static/community_logos/python-logo.png)" ] } ], "metadata": {} } ] }