{ "metadata": { "name": "" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Basics of Python - 2\n", "====================================\n", "\n", "by Kaustubh Vaghmare\n", "---------------------\n", "(IUCAA, Pune)\n", "\n", "E-mail: kaustubh[at]iucaa[dot]ernet[dot]in\n" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Our First Program - Rewritten!\n", "------------------------------\n", "\n", "Let us introduce the following modifications to the program.\n", "\n", "* We use floats instead of ints.\n", "* We accept the numbers from the user instead of \"hard coding\" them." ] }, { "cell_type": "code", "collapsed": false, "input": [ "# Modified first program.\n", "a = raw_input(\"Please enter number 1: \")\n", "b = raw_input(\"Please enter number 2: \")\n", "\n", "c, d = a+b, a-b\n", "q, r = a/b, a*b\n", "\n", "print c,d,q,r" ], "language": "python", "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "stream": "stdout", "text": [ "Please enter number 1: 5.0\n" ] }, { "name": "stdout", "output_type": "stream", "stream": "stdout", "text": [ "Please enter number 2: 2.5\n" ] }, { "ename": "TypeError", "evalue": "unsupported operand type(s) for -: 'str' and 'str'", "output_type": "pyerr", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m\n\u001b[1;31mTypeError\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 3\u001b[0m \u001b[0mb\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mraw_input\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"Please enter number 2: \"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 4\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 5\u001b[1;33m \u001b[0mc\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0md\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0ma\u001b[0m\u001b[1;33m+\u001b[0m\u001b[0mb\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0ma\u001b[0m\u001b[1;33m-\u001b[0m\u001b[0mb\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 6\u001b[0m \u001b[0mq\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mr\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0ma\u001b[0m\u001b[1;33m/\u001b[0m\u001b[0mb\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0ma\u001b[0m\u001b[1;33m*\u001b[0m\u001b[0mb\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 7\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n", "\u001b[1;31mTypeError\u001b[0m: unsupported operand type(s) for -: 'str' and 'str'" ] } ], "prompt_number": 1 }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "What happened?\n", "--------------\n", "\n", "* Anything input through the keyboard using raw_input() is ... a \"string\".\n", "* Strings support addition (concatenation) but nothing else.\n", "\n", "So what should we do?\n", "---------------\n", "\n", "* \"3.0\" is a string. 3.0 is a float!\n", "* To convert \"3.0\" into a string, we use a simple function - float(\"3.0\")\n", "\n", "So, let's rewrite our program!" ] }, { "cell_type": "code", "collapsed": false, "input": [ "a = float( raw_input(\"Enter Number 1: \") )\n", "b = float( raw_input(\"Enter Number 2: \") )\n", "\n", "c,d = a+b, a-b\n", "q,r = a*b, a/b\n", "\n", "print \"Addition = %f, Difference = %f \" % (c,d)\n", "print \"Division = %f, Quotient = %f\" % (q,r)" ], "language": "python", "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "stream": "stdout", "text": [ "Enter Number 1: 5.0\n" ] }, { "name": "stdout", "output_type": "stream", "stream": "stdout", "text": [ "Enter Number 2: 2.5\n" ] }, { "output_type": "stream", "stream": "stdout", "text": [ "Addition = 7.500000, Difference = 2.500000 \n", "Division = 12.500000, Quotient = 2.000000\n" ] } ], "prompt_number": 2 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Yuck! That ugly output! Wish I could control the decimal places..." ] }, { "cell_type": "code", "collapsed": false, "input": [ "a = float( raw_input(\"Enter Number 1: \") )\n", "b = float( raw_input(\"Enter Number 2: \") )\n", "\n", "c,d = a+b, a-b\n", "q,r = a*b, a/b\n", "\n", "print \"Addition = %.2f, Difference = %.2f \" % (c,d)\n", "print \"Division = %.2f, Quotient = %.2f\" % (q,r)" ], "language": "python", "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "stream": "stdout", "text": [ "Enter Number 1: 5.0\n" ] }, { "name": "stdout", "output_type": "stream", "stream": "stdout", "text": [ "Enter Number 2: 2.5\n" ] }, { "output_type": "stream", "stream": "stdout", "text": [ "Addition = 7.50, Difference = 2.50 \n", "Division = 12.50, Quotient = 2.00\n" ] } ], "prompt_number": 3 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Ah! Now, that's much better." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "String Formatting\n", "----------\n", "\n", "We have seen a powerful of constructing strings in the previous example." ] }, { "cell_type": "code", "collapsed": false, "input": [ "print \"Addition = %.2f, Difference = %.2f \" % (c,d)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Addition = 7.50, Difference = 2.50 \n" ] } ], "prompt_number": 4 }, { "cell_type": "markdown", "metadata": {}, "source": [ "C / FORTRAN users will immediately understand this method of string construction.\n", "\n", "Python supports this and its own way of string formatting.\n", "-------" ] }, { "cell_type": "code", "collapsed": false, "input": [ "gal_name = \"NGC 7709\"; int_bmagnitude = 13.6" ], "language": "python", "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [], "prompt_number": 5 }, { "cell_type": "code", "collapsed": false, "input": [ "statement1 = \"The galaxy %s has an integrated \\\n", "B-band magnitude of %.2f\" % (gal_name, int_bmagnitude)" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 6 }, { "cell_type": "code", "collapsed": false, "input": [ "statement2 = \"The galaxy {0:s} has an integrated \\\n", "B-band magnitude of {1:.2f}\".format(gal_name, int_bmagnitude)" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 7 }, { "cell_type": "code", "collapsed": false, "input": [ "statement3 = \"The galaxy {name:s} has an integrated \\\n", "B-band magnitude of {mag:.2f}\".format(name=gal_name, mag=int_bmagnitude)" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 8 }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "All the above statements are equivalent!\n", "------" ] }, { "cell_type": "code", "collapsed": false, "input": [ "print statement1, \"\\n\", statement2, \"\\n\", statement3, \"\\n\"" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "The galaxy NGC 7709 has an integrated B-band magnitude of 13.60 \n", "The galaxy NGC 7709 has an integrated B-band magnitude of 13.60 \n", "The galaxy NGC 7709 has an integrated B-band magnitude of 13.60 \n", "\n" ] } ], "prompt_number": 15 }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can choose whichever method you like!\n", "\n", "As a former C/C++ user, I tend to use the first method.\n", "\n", "But ... second and third methods are more \"Pythonic\"." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Raw Strings\n", "------------\n", "\n", "* We have seen the three methods of string declaration. \n", "* We have also seen string formatting.\n", "* String formatting taught us that symbols like { or % have special meanings." ] }, { "cell_type": "code", "collapsed": false, "input": [ "# There is a special way of declaring strings where\n", "# we can ask Python to ignore all these symbols.\n", "raw_string = r\"Here is a percentage sign % and a brace }\"\n", "print raw_string" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Here is a percentage sign % and a brace }\n" ] } ], "prompt_number": 1 }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "Usefulness of Raw Strings - Example\n", "-------\n", "\n", "* Typically, when we make plots and set labels, we would like to invoke a LaTeX parser.\n", "* This would involve a lot \\ $ and {}. \n", "\n", "In such cases, it's best to use raw strings.\n", "\n", " plt.xlabel(r\" \\log \\rm{F}_v\")\n", " \n", "Other examples, writing Windows file paths, XML code, HTML code, etc." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Conditionals\n", "------" ] }, { "cell_type": "code", "collapsed": false, "input": [ "num = int( raw_input(\"Enter number: \") )\n", "if num %2 == 0:\n", " print \"%d is even!\" % num\n", "else:\n", " print \"%d is odd!\" % num" ], "language": "python", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "stream": "stdout", "text": [ "Enter number: 3\n" ] }, { "output_type": "stream", "stream": "stdout", "text": [ "3 is odd!\n" ] } ], "prompt_number": 16 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let us write something bigger..." ] }, { "cell_type": "code", "collapsed": false, "input": [ "model_choice = int(raw_input( \"Enter choice [1 or 2]: \") )\n", "spectra = 3 # In realistic case, this will be some complicated object.\n", "\n", "if model_choice == 1:\n", " model1(spectra)\n", " print \"Model 1 fitted.\"\n", "elif model_choice == 2:\n", " model2(spectra)\n", " print \"Model 2 fitted.\"\n", "else:\n", " print \"Invalid model entered.\"" ], "language": "python", "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "stream": "stdout", "text": [ "Enter choice [1 or 2]: 1\n" ] }, { "output_type": "stream", "stream": "stdout", "text": [ "Model 1 fitted.\n" ] } ], "prompt_number": 2 }, { "cell_type": "markdown", "metadata": {}, "source": [ "What do you notice apart from the syntax in the above example?\n", "------" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "Indentation - A Vital Part of the Pythonic Way\n", "--------------\n", "\n", "Be it the if-block illustrated above or the loops or the functions (to come soon), indentation is at the heart of the Python's way of doing things!\n", "\n", "Function definitions, loops, if-blocks - nothing has your typical boundaries like { } as in C/C++/Java.\n", "\n", "The \"level of the indentation\" defines the scope of a \"block\"." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "In support of indentation\n", "------\n", "\n", "Look at the following C-like code.\n", "\n", " if (x>0)\n", " if (y>0)\n", " print \"Woohoo!\"\n", " else\n", " print \"Booboo!\"\n", " \n", "Which \"if\" does the \"else\" belong to?\n", "\n", "In C like languages, the braces {}s do the marking, the indentation is purely optional. In Python, indentation levels determine scopes. In Python the \"the else\" belongs to \"if (x>0)\". \n", "\n", "Python forces you to write clean code! (Obfuscation lovers, go to hell!)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Wrapping up if-elif-else\n", "-------\n", "\n", "The general syntax:\n", "\n", " if :\n", " do this\n", " and this\n", " elif :\n", " this\n", " and this\n", " ...\n", " else:\n", " do this \n", " and this\n", " " ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "Conditions are anything that return True or False.\n", "------\n", "\n", "* == (equal to)\n", "* !=\n", "* \\>\n", "* \\>=\n", "* < \n", "* <= \n", "\n", "You can combine conditionals using \"logical operators\"\n", "\n", "* and\n", "* or\n", "* not" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "The Boolean Data Type\n", "--------------" ] }, { "cell_type": "code", "collapsed": false, "input": [ "a = True\n", "b = False\n", "\n", "if a:\n", " print \"This comes on screen.\"\n", "\n", "if b:\n", " print \"This won't come on screen.\"" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "This comes on screen.\n" ] } ], "prompt_number": 3 }, { "cell_type": "code", "collapsed": false, "input": [ "type(a) # To check type of object." ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 4, "text": [ "bool" ] } ], "prompt_number": 4 }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "Almost Everything has a Boolean Equivalent\n", "------" ] }, { "cell_type": "code", "collapsed": false, "input": [ "a = 1\n", "b = 0\n", "\n", "if a:\n", " print \"Hello!\"\n", "if b:\n", " print \"Oh No!\"" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Hello!\n" ] } ], "prompt_number": 5 }, { "cell_type": "code", "collapsed": false, "input": [ "s1 = \"\"; s2 = \"Hello\"\n", "\n", "if s1:\n", " print \"Won't be printed.\"\n", "if s2:\n", " print \"Will be printed.\"" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Will be printed.\n" ] } ], "prompt_number": 8 }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Conditional Expression\n", "-------\n", "\n", "Consider..." ] }, { "cell_type": "code", "collapsed": false, "input": [ "if 5 > 6:\n", " x = 2\n", "else:\n", " x = 3" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 9 }, { "cell_type": "code", "collapsed": false, "input": [ "y = 2 if 5 > 6 else 3" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 10 }, { "cell_type": "code", "collapsed": false, "input": [ "print x,y" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "3 3\n" ] } ], "prompt_number": 11 }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "A Second Tour of the Data Types\n", "===========\n", "\n", "The two other data types we need to know:\n", "\n", "* Lists \n", "* Dictionaries\n", "\n", "Data Types we will not cover (formally):\n", "\n", "* Tuples (immutable lists!)\n", "* Sets (key-less dictionaries!)\n", "* Complex Numbers\n", "* Fractions\n", "* Decimals\n", "* Ordered Tuples ..." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Lists\n", "-----" ] }, { "cell_type": "code", "collapsed": false, "input": [ "a = [1,2,3,4] # simple ordered collection" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 12 }, { "cell_type": "code", "collapsed": false, "input": [ "b = [\"Hello\", 45, 7.64, True] # can be heterogeneous" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 13 }, { "cell_type": "code", "collapsed": false, "input": [ "a[0], a[-1], a[1:3] # All \"sequence\" operations supported." ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 14, "text": [ "(1, 4, [2, 3])" ] } ], "prompt_number": 14 }, { "cell_type": "code", "collapsed": false, "input": [ "b[0][1] # 2nd member of the 1st member" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 15, "text": [ "'e'" ] } ], "prompt_number": 15 }, { "cell_type": "code", "collapsed": false, "input": [ "a = [ [1,2,3] , [4,5,6] , [7,8,9] ] # list of lists allowed." ], "language": "python", "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [], "prompt_number": 16 }, { "cell_type": "code", "collapsed": false, "input": [ "a[2][1] # Accessing elements in nested structures." ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 17, "text": [ "8" ] } ], "prompt_number": 17 }, { "cell_type": "code", "collapsed": false, "input": [ "[1,3,4] + [5,6,7] # Support concatenation" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 18, "text": [ "[1, 3, 4, 5, 6, 7]" ] } ], "prompt_number": 18 }, { "cell_type": "code", "collapsed": false, "input": [ "[1,6,8] * 3 # Repetition (like strings)" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 19, "text": [ "[1, 6, 8, 1, 6, 8, 1, 6, 8]" ] } ], "prompt_number": 19 }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Lists are Mutable! (Strings are not!)\n", "----" ] }, { "cell_type": "code", "collapsed": false, "input": [ "a = [1,4,5,7]" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 20 }, { "cell_type": "code", "collapsed": false, "input": [ "print a" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "[1, 4, 5, 7]\n" ] } ], "prompt_number": 21 }, { "cell_type": "code", "collapsed": false, "input": [ "a[2] = 777" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 22 }, { "cell_type": "code", "collapsed": false, "input": [ "print a" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "[1, 4, 777, 7]\n" ] } ], "prompt_number": 23 }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "List Methods\n", "----" ] }, { "cell_type": "code", "collapsed": false, "input": [ "a = [1,3,5]\n", "print a" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "[1, 3, 5]\n" ] } ], "prompt_number": 27 }, { "cell_type": "code", "collapsed": false, "input": [ "a.append(7) # adds an element to the end\n", "print a # the list has changed (unlike string methods!)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "[1, 3, 5, 7]\n" ] } ], "prompt_number": 28 }, { "cell_type": "code", "collapsed": false, "input": [ "a.extend([9,11,13]) # concatenates a list at the end\n", "print a" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "[1, 3, 5, 7, 9, 11, 13]\n" ] } ], "prompt_number": 29 }, { "cell_type": "code", "collapsed": false, "input": [ "print a" ], "language": "python", "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "[1, 3, 5, 7, 9, 11, 13]\n" ] } ], "prompt_number": 30 }, { "cell_type": "code", "collapsed": false, "input": [ "a.pop() # Removes one element at the end.\n", "print a" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "[1, 3, 5, 7, 9, 11]\n" ] } ], "prompt_number": 31 }, { "cell_type": "code", "collapsed": false, "input": [ "a.pop(2) # Removes 3rd element. \n", "print a" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "[1, 3, 7, 9, 11]\n" ] } ], "prompt_number": 32 }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Don't Forget!!!\n", "-----\n" ] }, { "cell_type": "code", "collapsed": false, "input": [ "print dir(a) # list of methods for a list \"a\"" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']\n" ] } ], "prompt_number": 33 }, { "cell_type": "code", "collapsed": false, "input": [ "help(a.sort)" ], "language": "python", "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Help on built-in function sort:\n", "\n", "sort(...)\n", " L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;\n", " cmp(x, y) -> -1, 0, 1\n", "\n" ] } ], "prompt_number": 34 }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Implications of Mutability\n", "----" ] }, { "cell_type": "code", "collapsed": false, "input": [ "l = [1,2,3,4]\n", "m = l\n", "\n", "l.append(5)\n", "print l\n", "print m" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "[1, 2, 3, 4, 5]\n", "[1, 2, 3, 4, 5]\n" ] } ], "prompt_number": 35 }, { "cell_type": "markdown", "metadata": {}, "source": [ "l and m point to the same object. When the object mutates, whether you refer to it using l or m, you get the same mutated object." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "How do I make a copy then?\n", "---" ] }, { "cell_type": "code", "collapsed": false, "input": [ "l = [1,2,3,4]\n", "m = l[:] \n", "\n", "l.append(5)\n", "print l\n", "print m" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "[1, 2, 3, 4, 5]\n", "[1, 2, 3, 4]\n" ] } ], "prompt_number": 36 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Python has a module called \"copy\" available for making copies. Will be covered later." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Dictionaries\n", "----\n", "\n", "* Imagine a list as a collection of objects obj0, obj1, obj2 ... \n", "* First object has a location 0, second 1 ... \n", "* Now, imagine renaming location 0 as \"something\", location 1 as \"somethingelse\" ...\n", "* Earlier, you accessed objects at numbered locations a[0].\n", "* Now, you access objects by specifying location names a[\"something\"]\n", "\n", "Let's see this at work." ] }, { "cell_type": "code", "collapsed": false, "input": [ "d1 = { \"a\" : 3, \"b\" : 5}\n", "print d1[\"a\"]\n", "print d1[\"b\"]" ], "language": "python", "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "3\n", "5\n" ] } ], "prompt_number": 37 }, { "cell_type": "markdown", "metadata": {}, "source": [ "\"a\", \"b\" are called keys and 3,5 are called values. So formally, a dictionary is a collection of key-value pairs." ] }, { "cell_type": "code", "collapsed": false, "input": [ "d1[\"c\"] = 7 # Since \"c\" does not exist, a new key-value pair is made.\n", "d1[\"a\"] = 1 # SInce \"a\" exists already, value is modified.\n", "print d1 # You will notice the order is not the same." ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "{'a': 1, 'c': 7, 'b': 5}\n" ] } ], "prompt_number": 38 }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "Dictionary Methods\n", "----" ] }, { "cell_type": "code", "collapsed": false, "input": [ "keys = d1.keys() # Returns a list of all keys which is stored in \"keys\".\n", "print keys" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "['a', 'c', 'b']\n" ] } ], "prompt_number": 39 }, { "cell_type": "code", "collapsed": false, "input": [ "values = d1.values() # Returns a list of values.\n", "print values" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "[1, 7, 5]\n" ] } ], "prompt_number": 40 }, { "cell_type": "code", "collapsed": false, "input": [ "d1.items() # List of Tuples of key-value pairs." ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 41, "text": [ "[('a', 1), ('c', 7), ('b', 5)]" ] } ], "prompt_number": 41 }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "Defining Dictionaries - ways to do this\n", "-----" ] }, { "cell_type": "code", "collapsed": false, "input": [ "d1 = {\"a\":3, \"b\":5, \"c\":7} # we've seen this." ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 42 }, { "cell_type": "code", "collapsed": false, "input": [ "keys = [\"a\", \"b\", \"c\"]\n", "values = [3,5,7]\n", "d2 = dict( zip(keys,values) ) # creates dictionary similar to d2" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 43 }, { "cell_type": "code", "collapsed": false, "input": [ "d3 = dict( a=3, b=5, c=7) # again, same as d1,d2" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 44 }, { "cell_type": "code", "collapsed": false, "input": [ "d4 = dict( [ (\"a\",3), (\"b\",5), (\"c\",7) ] ) # same as d1,d2,d3" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 45 }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Loop Loop Loop\n", "-------" ] }, { "cell_type": "code", "collapsed": false, "input": [ "x = 0\n", "while x<5:\n", " print x, # NOTICE the comma at the end. Suppresses new line.\n", " x += 1" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "0 1 2 3 4\n" ] } ], "prompt_number": 46 }, { "cell_type": "code", "collapsed": false, "input": [ "x = 1\n", "while True:\n", " print \"x = %d\" % x\n", " choice = raw_input(\"Do you want to continue? \") \n", " if choice != \"y\":\n", " break # This statement breaks the loop.\n", " else:\n", " x += 1\n", " " ], "language": "python", "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "x = 1\n" ] }, { "name": "stdout", "output_type": "stream", "stream": "stdout", "text": [ "Do you want to continue? y\n" ] }, { "output_type": "stream", "stream": "stdout", "text": [ "x = 2\n" ] }, { "name": "stdout", "output_type": "stream", "stream": "stdout", "text": [ "Do you want to continue? y\n" ] }, { "output_type": "stream", "stream": "stdout", "text": [ "x = 3\n" ] }, { "name": "stdout", "output_type": "stream", "stream": "stdout", "text": [ "Do you want to continue? q\n" ] } ], "prompt_number": 49 }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "The \"for\" loop - Pay Attention!\n", "-----\n" ] }, { "cell_type": "code", "collapsed": false, "input": [ "x = [5,6,7,8,9,0] # a simple list\n", "for i in x:\n", " print i" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "5\n", "6\n", "7\n", "8\n", "9\n", "0\n" ] } ], "prompt_number": 51 }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "In \" for i in x\", x can be anything that is a collection of things." ] }, { "cell_type": "code", "collapsed": false, "input": [ "s = \"Hello!\"\n", "\n", "for c in s:\n", " print c" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "H\n", "e\n", "l\n", "l\n", "o\n", "!\n" ] } ], "prompt_number": 52 }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "No No No! I my good old for-loop back which generates numbers x to y in steps of z!!!" ] }, { "cell_type": "code", "collapsed": false, "input": [ "# OKAY!!! Let's try something here.\n", "\n", "for i in range(2,15,3):\n", " print i" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "2\n", "5\n", "8\n", "11\n", "14\n" ] } ], "prompt_number": 53 }, { "cell_type": "code", "collapsed": false, "input": [ "range(10) " ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 54, "text": [ "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]" ] } ], "prompt_number": 54 }, { "cell_type": "code", "collapsed": false, "input": [ "range(2,10)" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 55, "text": [ "[2, 3, 4, 5, 6, 7, 8, 9]" ] } ], "prompt_number": 55 }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "Let us see some wicked for-loops." ] }, { "cell_type": "code", "collapsed": false, "input": [ "a = [1,2,3,4,5]\n", "b = \"Hello\"\n", "c = zip(a,b)\n", "print c\n", "\n", "for i,j in c:\n", " print i, j" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "[(1, 'H'), (2, 'e'), (3, 'l'), (4, 'l'), (5, 'o')]\n", "1 H\n", "2 e\n", "3 l\n", "4 l\n", "5 o\n" ] } ], "prompt_number": 56 }, { "cell_type": "code", "collapsed": false, "input": [ "a = \"Hello!\"\n", "\n", "for i, c in enumerate(a):\n", " print \"Character no. %d is %s\" % (i+1, c)\n", "\n" ], "language": "python", "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Character no. 1 is H\n", "Character no. 2 is e\n", "Character no. 3 is l\n", "Character no. 4 is l\n", "Character no. 5 is o\n", "Character no. 6 is !\n" ] } ], "prompt_number": 57 }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "You can break and continue for-loops too!" ] }, { "cell_type": "code", "collapsed": false, "input": [ "for i in range(10000):\n", " if i%2 == 0: # Even\n", " print \"Even\"\n", " continue\n", " print \"Odd!\"\n", " \n", " if i == 7: # What if I had said \"i==8 or i==10\" ??????\n", " break" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Even\n", "Odd!\n", "Even\n", "Odd!\n", "Even\n", "Odd!\n", "Even\n", "Odd!\n" ] } ], "prompt_number": 60 }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Traversing Dictionaries using for-loops\n", "------" ] }, { "cell_type": "code", "collapsed": false, "input": [ "d = dict( a = 1, b = 2, c = 3, d = 4)\n", "\n", "for key,value in d.items():\n", " print key, \"-->\", value" ], "language": "python", "metadata": { "slideshow": { "slide_type": "-" } }, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "a --> 1\n", "c --> 3\n", "b --> 2\n", "d --> 4\n" ] } ], "prompt_number": 61 }, { "cell_type": "code", "collapsed": false, "input": [ "for key in d.keys():\n", " print key, \"-->\", d[key]" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "a --> 1\n", "c --> 3\n", "b --> 2\n", "d --> 4\n" ] } ], "prompt_number": 63 } ], "metadata": {} } ] }