{ "metadata": { "name": "" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Basics of Python\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": [ "Topics to be Covered\n", "====================\n", "(Not in any specific order.)\n", "\n", "* Basic I/O in Python\n", "* Data Types in Python\n", "* Programming Philosophy\n", "* Under The Hood\n", "* Conditionals\n", "* Loops\n", "* Basics of Objects and Methods\n", "* etc.\n", "\n" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "Assumptions!!!\n", "================\n", "\n", "You are not new to programming.\n", "-------------------------------\n", "(Will freely throw jargon around!)\n", "\n", "You are new to Python!\n", "-----------------------" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Python 2 or 3?\n", "==================\n", "\n", "* Python's key strength lies in its libraries.\n", "* These are not ready / optimized for Python 3 yet.\n", "* But they soon(!) will be! (Almost are!)\n", "\n", "Keep track of progress & Migrate!\n", "----------------------------------\n", "\n", "http://ptgmedia.pearsoncmg.com/imprint_downloads/informit/promotions/python/python2python3.pdf\n", "\n", "http://nbviewer.ipython.org/github/rasbt/python_reference/blob/master/tutorials/key_differences_between_python_2_and_3.ipynb\n", "\n", "https://pypi.python.org/pypi (select Python 3 Packages on the left)\n" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Our First Program!\n", "===================" ] }, { "cell_type": "code", "collapsed": false, "input": [ "a = 3\n", "b = 5\n", "c = a+b\n", "d = a-b\n", "q, r = a/b, a%b # Yes, this is allowed!\n", "\n", "# Now, let's print!\n", "print \"Hello World!\" # We just had to do this, did we not?\n", "print \"Sum, Difference = \", c, d\n", "print \"Quotient and Remainder = \", q, r" ], "language": "python", "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Hello World!\n", "Sum, Difference = 8 -2\n", "Quotient and Remainder = 0 3\n" ] } ], "prompt_number": 1 }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "What can we learn from this simple program?\n", "-----" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "Dynamic Typing\n", "--------------\n", "\n", "* We don't declare variables and types in advance. (dynamic typing)\n", "* Variables created when first assigned values.\n", "* Variables don't exist if not assigned. (strong typing)\n", "\n", "Commenting\n", "----------\n", "\n", "Everything after # is a comment and is ignored. Comment freely\n", "\n", "\"print\" statement\n", "------------------\n", "\n", "Replaced by a print() function in Python 3.\n", "\n", "Tuple unpacking assignments\n", "----------------------------\n", "\n", " a,b = 5,6\n", "\n", "More complicated forms introduced in Python 3." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "Other Things\n", "==================\n", "\n", "* Behavior of / and % operators with integer types. (/ changes in Python 3)\n", "* No termination symbols at end of Python statements.\n", "* Exception to the above...\n", "\n", " a = 3; b = 5\n", " " ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Under the Hood\n", "===================\n", "\n", "* No explicit compiling/linking step. Just run...\n", " $ python First.py\n", "* Internally, program translated into bytecode (.pyc files)\n", "* The \"translation + execution\" happens line-by-line\n", "\n", "Implications of \"line-by-line\" style\n", "-------------------------------------\n", "\n", "* N lines will be executed before error on N+1th line haults program!\n", "* An interactive shell." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "[ Interactive Shell Demo ]\n", "===========================" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "[ Introduction to iPython ] \n", "=============================" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "The First Tour of the Data Types\n", "================================\n", "\n", "* Numbers - Integers\n", "* Numbers - Floats\n", "\n", "(Exploration of math module)\n", "\n", "* Strings \n", "\n", "(Methods of Declaring Strings)\n", "\n", "(Concept of Sequences)\n", "\n", "(Concept of Slicing)\n", "\n", "(Concept of Mutability)\n", "\n", "(Introduction of Object.Method concepts)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Integers\n", "---------" ] }, { "cell_type": "code", "collapsed": false, "input": [ "8 ** 2 # Exponentiation" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 2, "text": [ "64" ] } ], "prompt_number": 2 }, { "cell_type": "code", "collapsed": false, "input": [ "23**100 # Auto-upgrade to \"LONG INT\" Notice the L!" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 3, "text": [ "14886191506363039393791556586559754231987119653801368686576988209222433278539331352152390143277346804233476592179447310859520222529876001L" ] } ], "prompt_number": 3 }, { "cell_type": "code", "collapsed": false, "input": [ "5 / 2, 5%2 # Quotient-Remainder Revisited." ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 4, "text": [ "(2, 1)" ] } ], "prompt_number": 4 }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Floats\n", "-------\n" ] }, { "cell_type": "code", "collapsed": false, "input": [ "5.0 * 2, 5*2.0 # Values upgraded to \"higher data type\"." ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 5, "text": [ "(10.0, 10.0)" ] } ], "prompt_number": 5 }, { "cell_type": "code", "collapsed": false, "input": [ "5**0.5 # Yes, it works! Square-root." ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 6, "text": [ "2.23606797749979" ] } ], "prompt_number": 6 }, { "cell_type": "code", "collapsed": false, "input": [ "5 / 4.0 # No longer a quotient." ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 7, "text": [ "1.25" ] } ], "prompt_number": 7 }, { "cell_type": "code", "collapsed": false, "input": [ "5 % 4.0, 5 % 4.1 # Remainder, yes!!!" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 47, "text": [ "(1.0, 0.9000000000000004)" ] } ], "prompt_number": 47 }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Math Module\n", "------------\n", "\n", "* A module can be thought of as a collection of related functions.\n", "* To use a module, \n", "\n", " import ModuleName\n", " \n", "* To use a function inside a module, simply say\n", "\n", " ModuleName.Function(inputs)\n", " \n", "Let's see the math module in action!" ] }, { "cell_type": "code", "collapsed": false, "input": [ "import math\n", "x = 45*math.pi/180.0\n", "math.sin(x)" ], "language": "python", "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 9, "text": [ "0.7071067811865475" ] } ], "prompt_number": 9 }, { "cell_type": "code", "collapsed": false, "input": [ "math.sin( math.radians(45) ) # nested functions" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 10, "text": [ "0.7071067811865475" ] } ], "prompt_number": 10 }, { "cell_type": "markdown", "metadata": {}, "source": [ "There are about 42 functions inside Math library! So, where can one get a quick reference of what these functions are, what they do and how to use them!?!?" ] }, { "cell_type": "code", "collapsed": false, "input": [ "print dir(math) # Prints all functions associated with Math module." ], "language": "python", "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "['__doc__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']\n" ] } ], "prompt_number": 11 }, { "cell_type": "code", "collapsed": false, "input": [ "help(math.hypot)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Help on built-in function hypot in module math:\n", "\n", "hypot(...)\n", " hypot(x, y)\n", " \n", " Return the Euclidean distance, sqrt(x*x + y*y).\n", "\n" ] } ], "prompt_number": 12 }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Strings\n", "--------\n", "There are three methods of defining strings." ] }, { "cell_type": "code", "collapsed": false, "input": [ "a = \"John's Computer\" # notice the '" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 13 }, { "cell_type": "code", "collapsed": false, "input": [ "b = 'John said, \"This is my computer.\"' # notice the \"" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 14 }, { "cell_type": "code", "collapsed": false, "input": [ "a_alt = 'John\\'s Computer' # now you need the escape sequence \\" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 15 }, { "cell_type": "code", "collapsed": false, "input": [ "b_alt = \"John said, \\\"This is my computer.\\\"\" # again escape sequence." ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 16 }, { "cell_type": "code", "collapsed": false, "input": [ "long_string = \"\"\"Hello World! \n", "\n", "I once said to people, \"Learn Python!\" \n", "\n", "And then they said, \"Organize a workshop!\" \"\"\"" ], "language": "python", "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [], "prompt_number": 17 }, { "cell_type": "code", "collapsed": false, "input": [ "long_string_traditional = 'Hello World! \\n\\nI once said to people, \"Learn Python!\" \\\n", "\\n\\nAnd then they said, \"Organize a workshop!\" '" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 18 }, { "cell_type": "markdown", "metadata": {}, "source": [ "* Can be used to dynamically build scripts, both Python-based and other \"languages\".\n", "* Used for documenting functions/modules. (To come later!)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "String Arithmetic\n", "----------------" ] }, { "cell_type": "code", "collapsed": false, "input": [ "s1 = \"Hello\" ; s2 = \"World!\"" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 19 }, { "cell_type": "code", "collapsed": false, "input": [ "string_sum = s1 + s2\n", "print string_sum" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "HelloWorld!\n" ] } ], "prompt_number": 20 }, { "cell_type": "code", "collapsed": false, "input": [ "string_product = s1*3\n", "print string_product" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "HelloHelloHello\n" ] } ], "prompt_number": 21 }, { "cell_type": "code", "collapsed": false, "input": [ "print s1*3+s2" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "HelloHelloHelloWorld!\n" ] } ], "prompt_number": 22 }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "String is a sequence!\n", "---------------------" ] }, { "cell_type": "code", "collapsed": false, "input": [ "a = \"Python rocks!\"" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 23 }, { "cell_type": "code", "collapsed": false, "input": [ "a[0], a[1], a[2] # Positions begin from 0 onwards." ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 24, "text": [ "('P', 'y', 't')" ] } ], "prompt_number": 24 }, { "cell_type": "code", "collapsed": false, "input": [ "a[-1], a[-2], a[-3] # Negative indices - count backwards!" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 25, "text": [ "('!', 's', 'k')" ] } ], "prompt_number": 25 }, { "cell_type": "code", "collapsed": false, "input": [ "len(a) # Measures length of both sequence/unordered collections!" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 26, "text": [ "13" ] } ], "prompt_number": 26 }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "Sequences can be sliced!\n", "----------" ] }, { "cell_type": "code", "collapsed": false, "input": [ "a[2:6] # elements with indices 2,3,4,5 but not 6" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 27, "text": [ "'thon'" ] } ], "prompt_number": 27 }, { "cell_type": "code", "collapsed": false, "input": [ "a[8:-2] # indices 8,9 ... upto 2nd last but not including it." ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 28, "text": [ "'ock'" ] } ], "prompt_number": 28 }, { "cell_type": "code", "collapsed": false, "input": [ "a[:5] # Missing first index, 0 assumed." ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 29, "text": [ "'Pytho'" ] } ], "prompt_number": 29 }, { "cell_type": "code", "collapsed": false, "input": [ "a[5:] # Missing last index, len(a) assumed." ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 30, "text": [ "'n rocks!'" ] } ], "prompt_number": 30 }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "Crazier Slicing\n", "---------------" ] }, { "cell_type": "code", "collapsed": false, "input": [ "a[1:6:2],a[1],a[3],a[5] # Indices 1, 3, 5" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 31, "text": [ "('yhn', 'y', 'h', 'n')" ] } ], "prompt_number": 31 }, { "cell_type": "code", "collapsed": false, "input": [ "a[::2] # beginning to end" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 32, "text": [ "'Pto ok!'" ] } ], "prompt_number": 32 }, { "cell_type": "code", "collapsed": false, "input": [ "a[::-1] # Reverse slicing!" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 33, "text": [ "'!skcor nohtyP'" ] } ], "prompt_number": 33 }, { "cell_type": "code", "collapsed": false, "input": [ "a[1:6:-1] # In a[i:j:-1], changes meaning of i and j" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 34, "text": [ "''" ] } ], "prompt_number": 34 }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Objects and Methods - A Crude Introduction\n", "------\n", "\n", "An object can be thought of a construct in the memory.\n", "\n", "It has a well defined behavior with respect to other objects. (2\\*3 is allowed, \"a\"\\*\"b\" is not!)\n", "\n", "The properties of the object, the operations that can be performed all are pre-defined.\n", "\n", "A method is a function bound to an object that can perform specific operations that the object supports.\n", "\n", " ObjectName.MethodName(arguments)\n", " \n", "OK, let's see some string methods in action!" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "String Methods\n", "--------------" ] }, { "cell_type": "code", "collapsed": false, "input": [ "a = \" I am a string, I am an object, I am immutable! \"" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 35 }, { "cell_type": "code", "collapsed": false, "input": [ "a.title()" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 36, "text": [ "' I Am A String, I Am An Object, I Am Immutable! '" ] } ], "prompt_number": 36 }, { "cell_type": "code", "collapsed": false, "input": [ "a.split(\",\")" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 37, "text": [ "[' I am a string', ' I am an object', ' I am immutable! ']" ] } ], "prompt_number": 37 }, { "cell_type": "code", "collapsed": false, "input": [ "a.strip() # Remove trailing and leading whitespaces." ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 38, "text": [ "'I am a string, I am an object, I am immutable!'" ] } ], "prompt_number": 38 }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "Strings are Immutable!\n", "-----------------------" ] }, { "cell_type": "code", "collapsed": false, "input": [ "print a # Check the value!" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ " I am a string, I am an object, I am immutable! \n" ] } ], "prompt_number": 39 }, { "cell_type": "code", "collapsed": false, "input": [ "a.title() # Transform string to title case ... really?" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 40, "text": [ "' I Am A String, I Am An Object, I Am Immutable! '" ] } ], "prompt_number": 40 }, { "cell_type": "code", "collapsed": false, "input": [ "print a # Nothing changed! Strings are immutabe." ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ " I am a string, I am an object, I am immutable! \n" ] } ], "prompt_number": 41 }, { "cell_type": "code", "collapsed": false, "input": [ "b = a.title() # String methods return strings instead." ], "language": "python", "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [], "prompt_number": 42 }, { "cell_type": "code", "collapsed": false, "input": [ "print b" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ " I Am A String, I Am An Object, I Am Immutable! \n" ] } ], "prompt_number": 43 }, { "cell_type": "code", "collapsed": false, "input": [ "a[3] = \"x\" # Immutability implies no in-place changes." ], "language": "python", "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "'str' object does not support item assignment", "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[1;32m----> 1\u001b[1;33m \u001b[0ma\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;36m3\u001b[0m\u001b[1;33m]\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;34m\"x\"\u001b[0m \u001b[1;31m# Immutability implies no in-place changes.\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[1;31mTypeError\u001b[0m: 'str' object does not support item assignment" ] } ], "prompt_number": 44 }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Getting Help\n", "-------------" ] }, { "cell_type": "code", "collapsed": false, "input": [ "print dir(a) # a is a string object." ], "language": "python", "metadata": { "slideshow": { "slide_type": "-" } }, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']\n" ] } ], "prompt_number": 45 }, { "cell_type": "code", "collapsed": false, "input": [ "help(a.find)" ], "language": "python", "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Help on built-in function find:\n", "\n", "find(...)\n", " S.find(sub [,start [,end]]) -> int\n", " \n", " Return the lowest index in S where substring sub is found,\n", " such that sub is contained within S[start:end]. Optional\n", " arguments start and end are interpreted as in slice notation.\n", " \n", " Return -1 on failure.\n", "\n" ] } ], "prompt_number": 46 } ], "metadata": {} } ] }