\n", "\n", "##### This means that we have to be careful to indent our code correctly, or else we will get syntax errors. " ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "##### This enforces a consistent appearance aiding readability and avoiding common errors.\n" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# **`for` loop**:\n", "\n", "In Python, loops can be programmed in a number of different ways. The most common is the `for` loop, which is used together with iterable objects, such as lists. \n", "\n", "\n", "##### Check examples for basic syntax" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "for x in [1,2,3]:\n", " print(x)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "for x in range(-3,3):\n", " print(x)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "##### Notice the use of **range** in the above code" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##### Syntax is \n", "\n", "##### for **variable** in **iterator**:" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# One more example using text list" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "things = ['tv', 'laptop', 'chair', 'mobile', 'table']\n", "for name in things:\n", " print name" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Questions for you" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "# find the square of first 1 to 10 numbers using for loop\n", "\n", "\n", "\n", "\n", "\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "# Write a program to iterate find len of each word from the below text\n", "text = \"Do what is right not what is easy\" \n", "\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# Write a program to find if text contains the word \"hard\" \n", "text = \"Do what is right not what is easy\"\n", "\n", "\n" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# List comprehensions" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "##### List comprehensions are a tool for transforming one list (any iterable actually) into another list. " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "print [num**2 for num in range(1,11)]" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "a= [(word,len(word)) for word in text.split()]" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "print a\n", "print type(a[0])" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# **`while` loop**:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "i = 0\n", "while i < 5:\n", " print(i)\n", " \n", " i = i + 1\n", " \n", "print(\"done\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# another example\n", "i=0\n", "while True:\n", " print i,\n", " i+=1\n", " if (i >5):\n", " break\n", "print \"done!\"" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# **Functions**\n" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "##### A function in Python is defined using the keyword `def`, followed by a function name, a signature within parentheses `()`, and a colon `:`. " ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "##### The following code, with one additional level of indentation, is the function body." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "# Defined using the def keyword\n", "def testFunction(): \n", " print(\"If at first you don’t succeed; call it version 1.0.!!\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "testFunction()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "slide" } }, "outputs": [], "source": [ "def func1(s):\n", " \"\"\"\n", " Print a string 's' and tell how many characters it has \n", " \"\"\"\n", " \n", " print(s + \" has \" + str(len(s)) + \" characters\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "help(func1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##### Notice the doc string" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "func1(\"Python is cool\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "slide" } }, "outputs": [], "source": [ "help(testFunction)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "# So always write a doc string... \n", "\n" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "##### Return is optional and then you effectively get a “procedure” but a None value is returned" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##### Define some functions that return and take a argument" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "def square(x):\n", " \"\"\"\n", " Return the square of x.\n", " \"\"\"\n", " return x ** 2" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "square(4)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "slide" } }, "outputs": [], "source": [ "# Functions can return multiple values\n", "def powers(x):\n", " \"\"\"\n", " Return a few powers of x.\n", " \"\"\"\n", " return x ** 2, x ** 3, x ** 4" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "powers(4)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# Calling function using keywords\n", "powers(x=2)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Remember:\n", "\n", "##### All objects including functions can be passed.\n", "##### Default arguments must follow all non-default arguments.\n", "##### Two special argument catchers.\n", "##### ** *x ** puts all remaining positional args into a list x. Must come after all normal argusments and defaults\n", "##### double x pulls all remaining args in a dictionary\n" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Questions for you" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "# write a function to write out times tables for a given number\n", "# 9 x 1 = 9\n", "# 9 x 2 = 18\n", "# etc\n", "\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "# write a function that calculates distance between two points (x1,y1) (x2,y2)\n", "x1,y1 = 0.0,0.0\n", "x2,y2 = 10.0,10.0\n", "\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "notes" } }, "outputs": [], "source": [ "# write a function that takes a text string and returns a dictonary of word and its len\n", "# \n", "text = \"Hard work beats talent when latent doesn't work hard\"\n", "\n", "\n", "\n", "\n", "\n", "\n" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "skip" } }, "source": [ " " ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# **Files**\n", "\n", "##### Files are objects that are created using the built in open function.\n", "\n", "\n", "##### f=**open**(filename,opt) \n", "\n", "##### opt can be **\"r\"**, **\"w\"** etc\n", "\n", "\n", "\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "# Lets open a file and write out our alist one line at a time into the file\n", "fp=open('ourfile.txt',\"w\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "for word in alist:\n", " fp.write(str(word)+'\\n')" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "fp.close()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "slide" } }, "outputs": [], "source": [ "!type ourfile.txt" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true, "slideshow": { "slide_type": "slide" } }, "outputs": [], "source": [ "# Lets write out the dictionary keys PriceList that we created earlier\n", "\n", "fp=open('ourfile2.txt',\"w\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "fp.writelines(PriceList.keys())" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "fp.close()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "!type ourfile2.txt" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# **Classes**\n" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "##### Classes are the key features of object-oriented programming. A class is a structure for representing an object and the operations that can be performed on the object. " ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "##### In Python a class can contain *attributes* (variables) and *methods* (functions)." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "##### A class is defined almost like a function, but using the `class` keyword, and the class definition usually contains a number of class method definitions (a function in a class)." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "* Each class method should have an argument `self` as it first argument. This object is a self-reference.\n", "\n", "* Some class method names have special meaning, for example:\n", "\n", " * `__init__`: The name of the method that is invoked when the object is first created.\n", " * `__str__` : A method that is invoked when a simple string representation of the class is needed, as for example when printed.\n", " * There are many more, see http://docs.python.org/2/reference/datamodel.html#special-method-names" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Lets define a Point class" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "slide" } }, "outputs": [], "source": [ "class Point:\n", " \"\"\"\n", " Simple class for representing a point in a Cartesian coordinate system.\n", " \"\"\"\n", " \n", " def __init__(self, x, y):\n", " \"\"\"\n", " Create a new Point at x, y.\n", " \"\"\"\n", " self.x = x\n", " self.y = y\n", " \n", " def translate(self, dx, dy):\n", " \"\"\"\n", " Translate the point by dx and dy in the x and y direction.\n", " \"\"\"\n", " self.x += dx\n", " self.y += dy\n", " \n", " \n", " def __str__(self):\n", " return(\"Point at [%f, %f]\" % (self.x, self.y))" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "##### To create a new instance of a class:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "p1 = Point(0, 0) # this will invoke the __init__ method in the Point class\n", "\n", "print(p1) # this will invoke the __str__ method" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "##### Lets check type" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "print (type(p1))" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "##### Lets check its methods" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "dir(p1)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "p2 = Point(1, 1)\n", "p1.translate(0.25, 1.5)\n", "\n", "print(p1)\n", "print(p2)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Questions for you" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "# Create a class rectangle, implement area and perimeter calculation as its methods\n", "\n", "class rectangle:\n", " \"\"\"\n", " Simple class for representing a rectangle.\n", " \n", " \"\"\"\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "##### Create a class to represent a simple cantilever beam\n", "\n", "$$\\delta_B = \\frac {F L^3} {3 E I}$$\n", "\n", "$$\\phi_B = \\frac {F L^2} {2 E I}$$\n", "where\n", "\n", "* F = Force acting on the tip of the beam\n", "* L = Length of the beam (span)\n", "* E = Modulus of elasticity\n", "* I = Area moment of inertia\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "# Cantilever class\n", "\n", "\n", "\n", "\n" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# **Modules**\n", "\n", "##### One of the most important concepts in good programming is to reuse code and avoid repetitions.\n", "\n", "\n", "\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##### The idea is to write functions and classes with a well-defined purpose and scope, and reuse these instead of repeating similar code in different part of a program (modular programming). The result is usually that readability and maintainability of a program is greatly improved. \n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##### What this means in practice is that our programs have fewer bugs, are easier to extend and debug/troubleshoot. \n", "\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##### Most of the functionality in Python is provided by *modules*. \n", "\n", "##### The Python Standard Library is a large collection of modules that provides *cross-platform* implementations of common facilities such as access to the operating system, file I/O, string management, network communication, and much more." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### References\n", " \n", " * The Python Language Reference: http://docs.python.org/2/reference/index.html\n", " * The Python Standard Library: http://docs.python.org/2/library/\n", "\n" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "##### To use a module in a Python program it first has to be imported. \n", "\n", "\n", "##### A module can be imported using the `import` statement. For example, to import the module `math`, which contains many standard mathematical functions, we can do:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "import math" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "##### This includes the whole module and makes it available for use later in the program. For example, we can do:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "x = math.cos(2 * math.pi)\n", "\n", "print(x)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# print the value of pi\n", "print math.pi" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "# Second method of importing (not recommended)\n", "from math import *\n", "\n", "x = cos(2 * pi)\n", "\n", "print(x)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# Third method of importing a module\n", "\n", "from math import cos,pi\n", "x=cos(2*pi)\n", "print x" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "skip" } }, "source": [ " " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Few Inbuilt modules" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# sys " ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "##### 1. path: contains the list of directions python imports from.\n", "##### 2. argv: a list of the arguments supplied on the command line.\n", "##### 3. stdin,stdout,stderr: file objects that handle the standard file handlers.\n" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# os" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "##### Generic operating system commands.\n", "##### **getcwd**, ***listdir(path)**, **system(cmd)**\n" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Json " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "import json" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "# Find what are its available methods\n", "print dir(json)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Tar file" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "import tarfile\n", "def untar(fname):\n", " if (fname.endswith(\"tar.gz\")):\n", " tar = tarfile.open(fname)\n", " tar.extractall()\n", " tar.close()\n", " print \"Extracted in Current Directory\"\n", " else:\n", " print \"Not a tar.gz file: '%s '\" % fname\n" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# We have just started, there lot you can do , so explore" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Thank You" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "skip" } }, "source": [ " " ] } ], "metadata": { "kernelspec": { "display_name": "Python 2", "language": "python", "name": "python2" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 2 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython2", "version": "2.7.11" } }, "nbformat": 4, "nbformat_minor": 0 }