Last active
August 29, 2015 14:04
-
-
Save drrosa/82783de856cba9beefa1 to your computer and use it in GitHub Desktop.
Python Tutorial for Programmers written with IPython Notebook
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| { | |
| "metadata": { | |
| "name": "", | |
| "signature": "sha256:ce403025c321d46ab0ff1ea37a1da73e71859741c171453f06ecd648df7693af" | |
| }, | |
| "nbformat": 3, | |
| "nbformat_minor": 0, | |
| "worksheets": [ | |
| { | |
| "cells": [ | |
| { | |
| "cell_type": "markdown", | |
| "metadata": {}, | |
| "source": [ | |
| "Python for Programmers (Answer Key)\n", | |
| "===\n", | |
| "Revision date: July 25, 2014\n", | |
| "\n", | |
| "[Get the latest version](http://nbviewer.ipython.org/urls/gist.githubusercontent.com/rosatamsen/82783de856cba9beefa1/raw/python_tutorial_answers.ipynb) \n", | |
| "[Got any feedback, error reports, or comments?](https://gist.github.com/rosatamsen/82783de856cba9beefa1#js-new-comment-form-actions)" | |
| ] | |
| }, | |
| { | |
| "cell_type": "markdown", | |
| "metadata": {}, | |
| "source": [ | |
| "####What\n", | |
| "This is a short interactive tutorial written in the IPython Notebook environment. It was designed for those who already know how to program and need a quick way to learn just enough to start reading and writing Python code and then continue on their own.\n", | |
| "\n", | |
| "####When\n", | |
| "The first part of this tutorial should take between 20 and 40 minutes depending on how long you experiment with the code.\n", | |
| "\n", | |
| "####How\n", | |
| "There are a number of cells containing skeleton code as a means of displaying a feature of the language in a generic way.\n", | |
| "\n", | |
| "1. Examine each cell.\n", | |
| "2. Complete, modify, or overwrite the skeleton code.\n", | |
| "3. Execute your code by pressing *Shift-Enter* to see the result.\n", | |
| "\n", | |
| "**HINTS:**\n", | |
| "- Although it seems like the cells are independent from one another, you can actually refer back to anything you have defined and executed previously.\n", | |
| "- If you get stuck, then have a look at the tutorial with answers." | |
| ] | |
| }, | |
| { | |
| "cell_type": "markdown", | |
| "metadata": {}, | |
| "source": [ | |
| "##Part I - Python Fundamentals" | |
| ] | |
| }, | |
| { | |
| "cell_type": "markdown", | |
| "metadata": {}, | |
| "source": [ | |
| "#####Commenting" | |
| ] | |
| }, | |
| { | |
| "cell_type": "code", | |
| "collapsed": false, | |
| "input": [ | |
| "# The pound/number (#) sign is used for one line comments.\n", | |
| "\"\"\" Three double quotes are used for\n", | |
| "multi line comments. \"\"\"" | |
| ], | |
| "language": "python", | |
| "metadata": {}, | |
| "outputs": [] | |
| }, | |
| { | |
| "cell_type": "markdown", | |
| "metadata": {}, | |
| "source": [ | |
| "#####Printing Values " | |
| ] | |
| }, | |
| { | |
| "cell_type": "code", | |
| "collapsed": false, | |
| "input": [ | |
| "print(\"Hello\") # replace \"value\" with an actual value" | |
| ], | |
| "language": "python", | |
| "metadata": {}, | |
| "outputs": [ | |
| { | |
| "output_type": "stream", | |
| "stream": "stdout", | |
| "text": [ | |
| "Hello\n" | |
| ] | |
| } | |
| ], | |
| "prompt_number": 1 | |
| }, | |
| { | |
| "cell_type": "code", | |
| "collapsed": false, | |
| "input": [ | |
| "# The print function can take any number of arguments and two optional args.\n", | |
| "print(\"Hello\", 123, \"-----\", 987, sep=\" *** \", end=\"END.\")" | |
| ], | |
| "language": "python", | |
| "metadata": {}, | |
| "outputs": [ | |
| { | |
| "output_type": "stream", | |
| "stream": "stdout", | |
| "text": [ | |
| "Hello *** 123 *** ----- *** 987END." | |
| ] | |
| } | |
| ], | |
| "prompt_number": 3 | |
| }, | |
| { | |
| "cell_type": "code", | |
| "collapsed": false, | |
| "input": [ | |
| "# String formatting syntax\n", | |
| "print(\"%d %s\" % (44, \"Some String\"))" | |
| ], | |
| "language": "python", | |
| "metadata": {}, | |
| "outputs": [] | |
| }, | |
| { | |
| "cell_type": "code", | |
| "collapsed": false, | |
| "input": [ | |
| "# Usually print() is not even needed, just input anything and execute it\n", | |
| "# This could be a number, a string, a variable or some other object\n", | |
| "\n", | |
| "2 + 3" | |
| ], | |
| "language": "python", | |
| "metadata": {}, | |
| "outputs": [ | |
| { | |
| "metadata": {}, | |
| "output_type": "pyout", | |
| "prompt_number": 4, | |
| "text": [ | |
| "5" | |
| ] | |
| } | |
| ], | |
| "prompt_number": 4 | |
| }, | |
| { | |
| "cell_type": "markdown", | |
| "metadata": {}, | |
| "source": [ | |
| "#####Functions/Methods\n", | |
| ">Python is an interpreted language, so function calls must go after function definitions." | |
| ] | |
| }, | |
| { | |
| "cell_type": "markdown", | |
| "metadata": {}, | |
| "source": [ | |
| "**Defining**" | |
| ] | |
| }, | |
| { | |
| "cell_type": "code", | |
| "collapsed": false, | |
| "input": [ | |
| "# Notice that indentation determines scope,\n", | |
| "# and function names are written in lowercase and with underscores by convention\n", | |
| "\n", | |
| "def function_name(first_arg, second_arg, third_arg, optional_arg=\"default_value\"):\n", | |
| " print(first_arg, second_arg, third_arg, optional_arg)\n", | |
| " \n", | |
| " return \"something\"" | |
| ], | |
| "language": "python", | |
| "metadata": {}, | |
| "outputs": [], | |
| "prompt_number": 14 | |
| }, | |
| { | |
| "cell_type": "markdown", | |
| "metadata": {}, | |
| "source": [ | |
| "**Calling**" | |
| ] | |
| }, | |
| { | |
| "cell_type": "code", | |
| "collapsed": false, | |
| "input": [ | |
| "\"\"\"\n", | |
| "If you change the function name from the previous cell,\n", | |
| "don't forget to re-execute the code in it, and update the function name in other cells.\n", | |
| "\"\"\"\n", | |
| "function_name(\"Hey\", \"oh\", \"let's go!\") # optional_arg takes on default_value" | |
| ], | |
| "language": "python", | |
| "metadata": {}, | |
| "outputs": [ | |
| { | |
| "output_type": "stream", | |
| "stream": "stdout", | |
| "text": [ | |
| "Hey oh let's go! default_value\n" | |
| ] | |
| }, | |
| { | |
| "metadata": {}, | |
| "output_type": "pyout", | |
| "prompt_number": 15, | |
| "text": [ | |
| "'something'" | |
| ] | |
| } | |
| ], | |
| "prompt_number": 15 | |
| }, | |
| { | |
| "cell_type": "code", | |
| "collapsed": false, | |
| "input": [ | |
| "s = function_name(\"Hey\", \"oh\", \"let's go!\", \"Not.\") # optional_arg takes on new value\n", | |
| "print(s)" | |
| ], | |
| "language": "python", | |
| "metadata": {}, | |
| "outputs": [ | |
| { | |
| "output_type": "stream", | |
| "stream": "stdout", | |
| "text": [ | |
| "Hey oh let's go! Not.\n", | |
| "something\n" | |
| ] | |
| } | |
| ], | |
| "prompt_number": 17 | |
| }, | |
| { | |
| "cell_type": "markdown", | |
| "metadata": {}, | |
| "source": [ | |
| "#####Variables\n", | |
| ">Everything in Python is an object." | |
| ] | |
| }, | |
| { | |
| "cell_type": "code", | |
| "collapsed": false, | |
| "input": [ | |
| "x = 1\n", | |
| "y = 2\n", | |
| "z = None # None represents the absence of a value\n", | |
| "\n", | |
| "print(x, y, z)\n", | |
| "\n", | |
| "x, y = y, x # Swap values\n", | |
| "\n", | |
| "print(x, y, z)" | |
| ], | |
| "language": "python", | |
| "metadata": {}, | |
| "outputs": [ | |
| { | |
| "output_type": "stream", | |
| "stream": "stdout", | |
| "text": [ | |
| "1 2 None\n", | |
| "2 1 None\n" | |
| ] | |
| } | |
| ], | |
| "prompt_number": 18 | |
| }, | |
| { | |
| "cell_type": "code", | |
| "collapsed": false, | |
| "input": [ | |
| "var_name = 1 # variables also use lowercase and underscores by convention\n", | |
| "\n", | |
| "def set_var_attempt():\n", | |
| " var_name = 2\n", | |
| " return var_name\n", | |
| "\n", | |
| "def set_var():\n", | |
| " global var_name # global only works when used within a function\n", | |
| " var_name = 3\n", | |
| " \n", | |
| "f = set_var_attempt # functions can be assigned to variables\n", | |
| "\n", | |
| "print(\"local var_name:\", var_name)\n", | |
| "print(\"local variable from set_var_attempt:\", f() )\n", | |
| "print(\"local var_name:\", var_name)\n", | |
| "set_var()\n", | |
| "print(\"global var_name:\", var_name)" | |
| ], | |
| "language": "python", | |
| "metadata": {}, | |
| "outputs": [ | |
| { | |
| "output_type": "stream", | |
| "stream": "stdout", | |
| "text": [ | |
| "local var_name: 1\n", | |
| "local variable from set_var_attempt: 2\n", | |
| "local var_name: 1\n", | |
| "global var_name: 3\n" | |
| ] | |
| } | |
| ], | |
| "prompt_number": 40 | |
| }, | |
| { | |
| "cell_type": "markdown", | |
| "metadata": {}, | |
| "source": [ | |
| "#####For Loops \n", | |
| ">range() returns an object that generates the numbers in the range on demand. " | |
| ] | |
| }, | |
| { | |
| "cell_type": "code", | |
| "collapsed": false, | |
| "input": [ | |
| "for i in range(5):\n", | |
| " print(i)" | |
| ], | |
| "language": "python", | |
| "metadata": {}, | |
| "outputs": [ | |
| { | |
| "output_type": "stream", | |
| "stream": "stdout", | |
| "text": [ | |
| "0\n", | |
| "1\n", | |
| "2\n", | |
| "3\n", | |
| "4\n" | |
| ] | |
| } | |
| ], | |
| "prompt_number": 41 | |
| }, | |
| { | |
| "cell_type": "code", | |
| "collapsed": false, | |
| "input": [ | |
| "for i in range(5, 11): # bounds are left inclusive and right exclusive\n", | |
| " print(i)" | |
| ], | |
| "language": "python", | |
| "metadata": {}, | |
| "outputs": [ | |
| { | |
| "output_type": "stream", | |
| "stream": "stdout", | |
| "text": [ | |
| "5\n", | |
| "6\n", | |
| "7\n", | |
| "8\n", | |
| "9\n", | |
| "10\n" | |
| ] | |
| } | |
| ], | |
| "prompt_number": 42 | |
| }, | |
| { | |
| "cell_type": "markdown", | |
| "metadata": {}, | |
| "source": [ | |
| "#####While Loops" | |
| ] | |
| }, | |
| { | |
| "cell_type": "code", | |
| "collapsed": false, | |
| "input": [ | |
| "i = 0\n", | |
| "while(i < 5):\n", | |
| " i+=1\n", | |
| " print(i)" | |
| ], | |
| "language": "python", | |
| "metadata": {}, | |
| "outputs": [ | |
| { | |
| "output_type": "stream", | |
| "stream": "stdout", | |
| "text": [ | |
| "1\n", | |
| "2\n", | |
| "3\n", | |
| "4\n", | |
| "5\n" | |
| ] | |
| } | |
| ], | |
| "prompt_number": 281 | |
| }, | |
| { | |
| "cell_type": "code", | |
| "collapsed": false, | |
| "input": [ | |
| "# This is just a busy-waiting while loop.\n", | |
| "\n", | |
| "while(True):\n", | |
| " pass # do nothing\n", | |
| " \n", | |
| "\"\"\"\n", | |
| "When your code has an infinite loop and just hangs,\n", | |
| "then you have to interrupt the Kernel to stop the loop\n", | |
| "by going to the top menu bar and clicking Kernel -> Interrupt.\n", | |
| "\"\"\"" | |
| ], | |
| "language": "python", | |
| "metadata": {}, | |
| "outputs": [ | |
| { | |
| "ename": "KeyboardInterrupt", | |
| "evalue": "", | |
| "output_type": "pyerr", | |
| "traceback": [ | |
| "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m\n\u001b[0;31mKeyboardInterrupt\u001b[0m Traceback (most recent call last)", | |
| "\u001b[0;32m<ipython-input-5-ca5a4c3f320e>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0;32mwhile\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;32mTrue\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 4\u001b[0;31m \u001b[0;32mpass\u001b[0m \u001b[0;31m# do nothing\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 5\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 6\u001b[0m \"\"\"\n", | |
| "\u001b[0;31mKeyboardInterrupt\u001b[0m: " | |
| ] | |
| } | |
| ], | |
| "prompt_number": 5 | |
| }, | |
| { | |
| "cell_type": "markdown", | |
| "metadata": {}, | |
| "source": [ | |
| "#####if-else Statements and Loop Control" | |
| ] | |
| }, | |
| { | |
| "cell_type": "code", | |
| "collapsed": false, | |
| "input": [ | |
| "for i in range(20):\n", | |
| " if i%2 == 0:\n", | |
| " print(i, \"is even\")\n", | |
| " elif i ==5:\n", | |
| " continue #skip the rest of the code inside this loop and start next iteration\n", | |
| " else:\n", | |
| " print(i, \"is odd\")\n", | |
| " if i == 10:\n", | |
| " break\n" | |
| ], | |
| "language": "python", | |
| "metadata": {}, | |
| "outputs": [ | |
| { | |
| "output_type": "stream", | |
| "stream": "stdout", | |
| "text": [ | |
| "0 is even\n", | |
| "1 is odd\n", | |
| "2 is even\n", | |
| "3 is odd\n", | |
| "4 is even\n", | |
| "6 is even\n", | |
| "7 is odd\n", | |
| "8 is even\n", | |
| "9 is odd\n", | |
| "10 is even\n" | |
| ] | |
| } | |
| ], | |
| "prompt_number": 1 | |
| }, | |
| { | |
| "cell_type": "markdown", | |
| "metadata": {}, | |
| "source": [ | |
| "##### Data Structures\n", | |
| ">A tuple, dictionary, or list can hold elements of different types." | |
| ] | |
| }, | |
| { | |
| "cell_type": "markdown", | |
| "metadata": {}, | |
| "source": [ | |
| "**Tuple**" | |
| ] | |
| }, | |
| { | |
| "cell_type": "code", | |
| "collapsed": false, | |
| "input": [ | |
| "tupl = (0, \"one\", 2 ,\"three\") # tuples are immutable\n", | |
| "print(tupl[0], tupl[3])" | |
| ], | |
| "language": "python", | |
| "metadata": {}, | |
| "outputs": [ | |
| { | |
| "output_type": "stream", | |
| "stream": "stdout", | |
| "text": [ | |
| "0 three\n" | |
| ] | |
| } | |
| ], | |
| "prompt_number": 10 | |
| }, | |
| { | |
| "cell_type": "code", | |
| "collapsed": false, | |
| "input": [ | |
| "# A tuple can also be created by simply writing comma-separted values\n", | |
| "def function_name():\n", | |
| " return \"one\", 2 ,\"three\" # so a function can return several values within a tuple" | |
| ], | |
| "language": "python", | |
| "metadata": {}, | |
| "outputs": [], | |
| "prompt_number": 13 | |
| }, | |
| { | |
| "cell_type": "code", | |
| "collapsed": false, | |
| "input": [ | |
| "# values within a tuple can be unpacked and assiged to variables\n", | |
| "a, b, c = function_name()\n", | |
| "print(a, b, c)" | |
| ], | |
| "language": "python", | |
| "metadata": {}, | |
| "outputs": [ | |
| { | |
| "output_type": "stream", | |
| "stream": "stdout", | |
| "text": [ | |
| "one 2 three\n" | |
| ] | |
| } | |
| ], | |
| "prompt_number": 14 | |
| }, | |
| { | |
| "cell_type": "markdown", | |
| "metadata": {}, | |
| "source": [ | |
| "**Dictionary/Hash**" | |
| ] | |
| }, | |
| { | |
| "cell_type": "code", | |
| "collapsed": false, | |
| "input": [ | |
| "d = {\"key\":\"value\", \"a\":1, \"b\":2}\n", | |
| "print(d[\"key\"])" | |
| ], | |
| "language": "python", | |
| "metadata": {}, | |
| "outputs": [ | |
| { | |
| "output_type": "stream", | |
| "stream": "stdout", | |
| "text": [ | |
| "value\n" | |
| ] | |
| } | |
| ], | |
| "prompt_number": 18 | |
| }, | |
| { | |
| "cell_type": "code", | |
| "collapsed": false, | |
| "input": [ | |
| "\"Value from key 'key' %(key)s and 'b' %(b)d\" % d #string substitution" | |
| ], | |
| "language": "python", | |
| "metadata": {}, | |
| "outputs": [ | |
| { | |
| "metadata": {}, | |
| "output_type": "pyout", | |
| "prompt_number": 25, | |
| "text": [ | |
| "\"Value from key 'key' value and 'b' 2\"" | |
| ] | |
| } | |
| ], | |
| "prompt_number": 25 | |
| }, | |
| { | |
| "cell_type": "markdown", | |
| "metadata": {}, | |
| "source": [ | |
| "**List/Array**" | |
| ] | |
| }, | |
| { | |
| "cell_type": "code", | |
| "collapsed": false, | |
| "input": [ | |
| "lst = range(10)\n", | |
| "print(lst) # returns a list of n integers starting from 0\n", | |
| "for i in lst:\n", | |
| " print(i, end=\", \")" | |
| ], | |
| "language": "python", | |
| "metadata": {}, | |
| "outputs": [ | |
| { | |
| "output_type": "stream", | |
| "stream": "stdout", | |
| "text": [ | |
| "range(0, 10)\n", | |
| "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " | |
| ] | |
| } | |
| ], | |
| "prompt_number": 32 | |
| }, | |
| { | |
| "cell_type": "code", | |
| "collapsed": false, | |
| "input": [ | |
| "lst = range(10, 21) # returns a range of integers as a list\n", | |
| "for i in lst:\n", | |
| " print(i, end=\", \")" | |
| ], | |
| "language": "python", | |
| "metadata": {}, | |
| "outputs": [ | |
| { | |
| "output_type": "stream", | |
| "stream": "stdout", | |
| "text": [ | |
| "10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, " | |
| ] | |
| } | |
| ], | |
| "prompt_number": 229 | |
| }, | |
| { | |
| "cell_type": "code", | |
| "collapsed": false, | |
| "input": [ | |
| "list_name = [0, \"one\", 2, \"three\", 4]\n", | |
| "list_name" | |
| ], | |
| "language": "python", | |
| "metadata": {}, | |
| "outputs": [ | |
| { | |
| "metadata": {}, | |
| "output_type": "pyout", | |
| "prompt_number": 8, | |
| "text": [ | |
| "[0, 'one', 2, 'three', 4]" | |
| ] | |
| } | |
| ], | |
| "prompt_number": 8 | |
| }, | |
| { | |
| "cell_type": "code", | |
| "collapsed": false, | |
| "input": [ | |
| "len(list_name) # length function" | |
| ], | |
| "language": "python", | |
| "metadata": {}, | |
| "outputs": [ | |
| { | |
| "metadata": {}, | |
| "output_type": "pyout", | |
| "prompt_number": 9, | |
| "text": [ | |
| "5" | |
| ] | |
| } | |
| ], | |
| "prompt_number": 9 | |
| }, | |
| { | |
| "cell_type": "code", | |
| "collapsed": false, | |
| "input": [ | |
| "list_name[-1] # use a negative number to access elements counting from the end" | |
| ], | |
| "language": "python", | |
| "metadata": {}, | |
| "outputs": [ | |
| { | |
| "metadata": {}, | |
| "output_type": "pyout", | |
| "prompt_number": 272, | |
| "text": [ | |
| "2" | |
| ] | |
| } | |
| ], | |
| "prompt_number": 272 | |
| }, | |
| { | |
| "cell_type": "code", | |
| "collapsed": false, | |
| "input": [ | |
| "list_name[1:4] # returns a slice of the same list" | |
| ], | |
| "language": "python", | |
| "metadata": {}, | |
| "outputs": [ | |
| { | |
| "metadata": {}, | |
| "output_type": "pyout", | |
| "prompt_number": 11, | |
| "text": [ | |
| "['one', 2, 'three']" | |
| ] | |
| } | |
| ], | |
| "prompt_number": 11 | |
| }, | |
| { | |
| "cell_type": "code", | |
| "collapsed": false, | |
| "input": [ | |
| "list_name[::2] # start, stop, and step are optional." | |
| ], | |
| "language": "python", | |
| "metadata": {}, | |
| "outputs": [ | |
| { | |
| "metadata": {}, | |
| "output_type": "pyout", | |
| "prompt_number": 12, | |
| "text": [ | |
| "[0, 2, 4]" | |
| ] | |
| } | |
| ], | |
| "prompt_number": 12 | |
| }, | |
| { | |
| "cell_type": "code", | |
| "collapsed": false, | |
| "input": [ | |
| "del list_name[3] # deletes element at index i\n", | |
| "print(list_name)" | |
| ], | |
| "language": "python", | |
| "metadata": {}, | |
| "outputs": [ | |
| { | |
| "output_type": "stream", | |
| "stream": "stdout", | |
| "text": [ | |
| "[0, 'one', 2]\n" | |
| ] | |
| } | |
| ], | |
| "prompt_number": 14 | |
| }, | |
| { | |
| "cell_type": "markdown", | |
| "metadata": {}, | |
| "source": [ | |
| "#####Syntactic Sugar\n", | |
| ">This is just syntax that can make things easier to read or express." | |
| ] | |
| }, | |
| { | |
| "cell_type": "markdown", | |
| "metadata": {}, | |
| "source": [ | |
| "**Boolean operators:** and, or, is, not" | |
| ] | |
| }, | |
| { | |
| "cell_type": "code", | |
| "collapsed": false, | |
| "input": [ | |
| "#Instead of the usual Boolean Operators: &&, ||\n", | |
| "#use the keywords: and, or\n", | |
| "\n", | |
| "print(\"True || False is\", True or False)\n", | |
| "print(\"True && False is\", True and False)\n", | |
| "\n", | |
| "\"\"\"\n", | |
| "The operator \"==\" and \"!=\" compare the values of two objects,\n", | |
| "whereas the keywords \"is\" and \"is not\" compare the references of two objects.\n", | |
| "\"\"\"\n", | |
| "\n", | |
| "#Given\n", | |
| "a = [1,2,3]\n", | |
| "b = [1,2,3]\n", | |
| "print(\"It is\", a == b, a == [1,2,3], [1,2,3] == [1,2,3], \"that a, b, and [1,2,3] have the same values. However,\")\n", | |
| "print(\"it is\", a is b, a is [1,2,3], [1,2,3] is [1,2,3], \"that a, b, and [1,2,3] are the same objects.\")" | |
| ], | |
| "language": "python", | |
| "metadata": {}, | |
| "outputs": [ | |
| { | |
| "output_type": "stream", | |
| "stream": "stdout", | |
| "text": [ | |
| "True || False is True\n", | |
| "True && False is False\n", | |
| "It is True True True that a, b, and [1,2,3] have the same values. However,\n", | |
| "it is False False False that a, b, and [1,2,3] are the same objects.\n" | |
| ] | |
| } | |
| ], | |
| "prompt_number": 232 | |
| }, | |
| { | |
| "cell_type": "markdown", | |
| "metadata": {}, | |
| "source": [ | |
| "**True vs False**" | |
| ] | |
| }, | |
| { | |
| "cell_type": "code", | |
| "collapsed": false, | |
| "input": [ | |
| "print(\"False evaluates to\", bool(False))\n", | |
| "print(\"The number 0 evaluates to\", bool(0))\n", | |
| "print(\"The keyword None evaluates to\", bool(None))\n", | |
| "print(\"Empty objects like strings or lists also evluate to\", bool(\"\"), bool([]))\n", | |
| "print(\"Everything else evaluates to\", bool(\"ASDF\"), bool(1234), bool([1]))" | |
| ], | |
| "language": "python", | |
| "metadata": {}, | |
| "outputs": [ | |
| { | |
| "output_type": "stream", | |
| "stream": "stdout", | |
| "text": [ | |
| "False evaluates to False\n", | |
| "The number 0 evaluates to False\n", | |
| "The keyword None evaluates to False\n", | |
| "Empty objects like strings or lists also evluate to False False\n", | |
| "Everything else evaluates to True True True\n" | |
| ] | |
| } | |
| ], | |
| "prompt_number": 233 | |
| }, | |
| { | |
| "cell_type": "markdown", | |
| "metadata": {}, | |
| "source": [ | |
| "**Shorthand**" | |
| ] | |
| }, | |
| { | |
| "cell_type": "code", | |
| "collapsed": false, | |
| "input": [ | |
| "# Given\n", | |
| "list_a = range(1,5)\n", | |
| "list_b = list_a\n", | |
| "\n", | |
| "# This one line\n", | |
| "print( [x * y for x in list_a for y in list_b] )\n", | |
| "\n", | |
| "# is equivalent to\n", | |
| "z = []\n", | |
| "for x in list_a:\n", | |
| " for y in list_b:\n", | |
| " z += [x*y]\n", | |
| "print(z)" | |
| ], | |
| "language": "python", | |
| "metadata": {}, | |
| "outputs": [ | |
| { | |
| "output_type": "stream", | |
| "stream": "stdout", | |
| "text": [ | |
| "[1, 2, 3, 4, 2, 4, 6, 8, 3, 6, 9, 12, 4, 8, 12, 16]\n", | |
| "[1, 2, 3, 4, 2, 4, 6, 8, 3, 6, 9, 12, 4, 8, 12, 16]\n" | |
| ] | |
| } | |
| ], | |
| "prompt_number": 234 | |
| }, | |
| { | |
| "cell_type": "code", | |
| "collapsed": false, | |
| "input": [ | |
| "# Conditions can be chained\n", | |
| "print( [x for x in z if 6 < x < 14] )" | |
| ], | |
| "language": "python", | |
| "metadata": {}, | |
| "outputs": [ | |
| { | |
| "output_type": "stream", | |
| "stream": "stdout", | |
| "text": [ | |
| "[8, 9, 12, 8, 12]\n" | |
| ] | |
| } | |
| ], | |
| "prompt_number": 235 | |
| }, | |
| { | |
| "cell_type": "markdown", | |
| "metadata": {}, | |
| "source": [ | |
| "#####Self Help" | |
| ] | |
| }, | |
| { | |
| "cell_type": "code", | |
| "collapsed": false, | |
| "input": [ | |
| "# Look for answers in Python's documentation by searching for Python keywords.\n", | |
| "\n", | |
| "help(\"print\")" | |
| ], | |
| "language": "python", | |
| "metadata": {}, | |
| "outputs": [ | |
| { | |
| "output_type": "stream", | |
| "stream": "stdout", | |
| "text": [ | |
| "Help on built-in function print in module builtins:\n", | |
| "\n", | |
| "print(...)\n", | |
| " print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n", | |
| " \n", | |
| " Prints the values to a stream, or to sys.stdout by default.\n", | |
| " Optional keyword arguments:\n", | |
| " file: a file-like object (stream); defaults to the current sys.stdout.\n", | |
| " sep: string inserted between values, default a space.\n", | |
| " end: string appended after the last value, default a newline.\n", | |
| " flush: whether to forcibly flush the stream.\n", | |
| "\n" | |
| ] | |
| } | |
| ], | |
| "prompt_number": 270 | |
| }, | |
| { | |
| "cell_type": "code", | |
| "collapsed": false, | |
| "input": [ | |
| "# prints out all attributes of an object\n", | |
| "dir(list)" | |
| ], | |
| "language": "python", | |
| "metadata": {}, | |
| "outputs": [ | |
| { | |
| "metadata": {}, | |
| "output_type": "pyout", | |
| "prompt_number": 225, | |
| "text": [ | |
| "['__add__',\n", | |
| " '__class__',\n", | |
| " '__contains__',\n", | |
| " '__delattr__',\n", | |
| " '__delitem__',\n", | |
| " '__dir__',\n", | |
| " '__doc__',\n", | |
| " '__eq__',\n", | |
| " '__format__',\n", | |
| " '__ge__',\n", | |
| " '__getattribute__',\n", | |
| " '__getitem__',\n", | |
| " '__gt__',\n", | |
| " '__hash__',\n", | |
| " '__iadd__',\n", | |
| " '__imul__',\n", | |
| " '__init__',\n", | |
| " '__iter__',\n", | |
| " '__le__',\n", | |
| " '__len__',\n", | |
| " '__lt__',\n", | |
| " '__mul__',\n", | |
| " '__ne__',\n", | |
| " '__new__',\n", | |
| " '__reduce__',\n", | |
| " '__reduce_ex__',\n", | |
| " '__repr__',\n", | |
| " '__reversed__',\n", | |
| " '__rmul__',\n", | |
| " '__setattr__',\n", | |
| " '__setitem__',\n", | |
| " '__sizeof__',\n", | |
| " '__str__',\n", | |
| " '__subclasshook__',\n", | |
| " 'append',\n", | |
| " 'clear',\n", | |
| " 'copy',\n", | |
| " 'count',\n", | |
| " 'extend',\n", | |
| " 'index',\n", | |
| " 'insert',\n", | |
| " 'pop',\n", | |
| " 'remove',\n", | |
| " 'reverse',\n", | |
| " 'sort']" | |
| ] | |
| } | |
| ], | |
| "prompt_number": 225 | |
| }, | |
| { | |
| "cell_type": "code", | |
| "collapsed": false, | |
| "input": [ | |
| "# get info about a specific attribute\n", | |
| "help(list.append)" | |
| ], | |
| "language": "python", | |
| "metadata": {}, | |
| "outputs": [ | |
| { | |
| "output_type": "stream", | |
| "stream": "stdout", | |
| "text": [ | |
| "Help on method_descriptor:\n", | |
| "\n", | |
| "append(...)\n", | |
| " L.append(object) -> None -- append object to end\n", | |
| "\n" | |
| ] | |
| } | |
| ], | |
| "prompt_number": 271 | |
| }, | |
| { | |
| "cell_type": "markdown", | |
| "metadata": {}, | |
| "source": [ | |
| "#####Miscellaneous" | |
| ] | |
| }, | |
| { | |
| "cell_type": "markdown", | |
| "metadata": {}, | |
| "source": [ | |
| "**String Literals**\n", | |
| ">String literals can be enclosed in matching single quotes (') or double quotes (\")." | |
| ] | |
| }, | |
| { | |
| "cell_type": "code", | |
| "collapsed": false, | |
| "input": [ | |
| "str = '''Triple double/single quotes actually create a string literal, so besides\n", | |
| " a multiple line comment, it can also be a multiple line string.'''\n", | |
| "\n", | |
| "print(str)" | |
| ], | |
| "language": "python", | |
| "metadata": {}, | |
| "outputs": [ | |
| { | |
| "output_type": "stream", | |
| "stream": "stdout", | |
| "text": [ | |
| "Triple double/single quotes actually create a string literal, so besides\n", | |
| " a multiple line comment, it can also be a multiple line string.\n" | |
| ] | |
| } | |
| ], | |
| "prompt_number": 253 | |
| }, | |
| { | |
| "cell_type": "markdown", | |
| "metadata": {}, | |
| "source": [ | |
| "**DocStrings**" | |
| ] | |
| }, | |
| { | |
| "cell_type": "code", | |
| "collapsed": false, | |
| "input": [ | |
| "def test_object():\n", | |
| " \"\"\"\n", | |
| " An object\u2019s docstring is defined by putting a string literal\n", | |
| " as the first statement of the attribute\u2019s definition.\n", | |
| " \"\"\"\n", | |
| " return 0\n", | |
| "\n", | |
| "print(test_object.__doc__) # prints out the docstring of an object" | |
| ], | |
| "language": "python", | |
| "metadata": {}, | |
| "outputs": [ | |
| { | |
| "output_type": "stream", | |
| "stream": "stdout", | |
| "text": [ | |
| "\n", | |
| " An object\u2019s docstring is defined by putting a string literal\n", | |
| " as the first statement of the attribute\u2019s definition.\n", | |
| " \n" | |
| ] | |
| } | |
| ], | |
| "prompt_number": 269 | |
| }, | |
| { | |
| "cell_type": "markdown", | |
| "metadata": {}, | |
| "source": [ | |
| "**Useful built-in functions**" | |
| ] | |
| }, | |
| { | |
| "cell_type": "code", | |
| "collapsed": false, | |
| "input": [ | |
| "# any() returns True if any item in the list satifies the condition.\n", | |
| "print( any( i<0 for i in range(0,5) ) )\n", | |
| "\n", | |
| "# returns the count of how many items make the condition true\n", | |
| "print( sum( 1 for i in range(0,5) if i>-1 ) )" | |
| ], | |
| "language": "python", | |
| "metadata": {}, | |
| "outputs": [ | |
| { | |
| "output_type": "stream", | |
| "stream": "stdout", | |
| "text": [ | |
| "False\n", | |
| "5\n" | |
| ] | |
| } | |
| ], | |
| "prompt_number": 273 | |
| }, | |
| { | |
| "cell_type": "markdown", | |
| "metadata": {}, | |
| "source": [ | |
| "This concludes the first part of the tutorial. Now you know enough to start writing your own scripts as well as continue learning more advanced Python." | |
| ] | |
| }, | |
| { | |
| "cell_type": "markdown", | |
| "metadata": {}, | |
| "source": [ | |
| "##Part II - Advanced Python" | |
| ] | |
| }, | |
| { | |
| "cell_type": "markdown", | |
| "metadata": {}, | |
| "source": [ | |
| "#####Importing Modules \n", | |
| ">A module is a file containing Python definitions and statements. The file name is the module name with the suffix *.py* appended." | |
| ] | |
| }, | |
| { | |
| "cell_type": "code", | |
| "collapsed": false, | |
| "input": [ | |
| "import module_name # also lowecase and underscores by convention" | |
| ], | |
| "language": "python", | |
| "metadata": {}, | |
| "outputs": [] | |
| }, | |
| { | |
| "cell_type": "code", | |
| "collapsed": false, | |
| "input": [ | |
| "from module_name import attribute_0, ..., attribute_n" | |
| ], | |
| "language": "python", | |
| "metadata": {}, | |
| "outputs": [] | |
| }, | |
| { | |
| "cell_type": "code", | |
| "collapsed": false, | |
| "input": [ | |
| "from module_name import * # star symbol means everything" | |
| ], | |
| "language": "python", | |
| "metadata": {}, | |
| "outputs": [] | |
| }, | |
| { | |
| "cell_type": "markdown", | |
| "metadata": {}, | |
| "source": [ | |
| "#####Class Definitions" | |
| ] | |
| }, | |
| { | |
| "cell_type": "code", | |
| "collapsed": false, | |
| "input": [ | |
| "# class names are written in UpperCamelCase by convention\n", | |
| "class ClassName:\n", | |
| " class_var = value\n", | |
| " \n", | |
| " def __init__(self, arg_0, ..., arg_n): # invoked when class is instantiated\n", | |
| " self.k = arg_0\n", | |
| " ... #instance variables\n", | |
| " self.n = arg_n\n", | |
| " \n", | |
| " def set_instance_var(self, new_value): #instance methods require self as first arg\n", | |
| " self.k = new_value\n", | |
| " \n", | |
| " def set_class_var(self, new_value):\n", | |
| " self.class_var = new_value" | |
| ], | |
| "language": "python", | |
| "metadata": {}, | |
| "outputs": [] | |
| }, | |
| { | |
| "cell_type": "code", | |
| "collapsed": false, | |
| "input": [ | |
| "class MultipleInheritance(ParentClass_0, ..., ParentClass_n)\n", | |
| " ..." | |
| ], | |
| "language": "python", | |
| "metadata": {}, | |
| "outputs": [] | |
| }, | |
| { | |
| "cell_type": "markdown", | |
| "metadata": {}, | |
| "source": [ | |
| "#####Class Instantiation" | |
| ] | |
| }, | |
| { | |
| "cell_type": "code", | |
| "collapsed": false, | |
| "input": [ | |
| "instance = ClassName(val_0, ..., val_n)\n", | |
| "other_instance = ClassName(val_0, ..., val_n)" | |
| ], | |
| "language": "python", | |
| "metadata": {}, | |
| "outputs": [] | |
| }, | |
| { | |
| "cell_type": "code", | |
| "collapsed": false, | |
| "input": [ | |
| "instance.k = new_value \n", | |
| "instance.set_instance_var(new_value) # self is passed automatically" | |
| ], | |
| "language": "python", | |
| "metadata": {}, | |
| "outputs": [] | |
| }, | |
| { | |
| "cell_type": "code", | |
| "collapsed": false, | |
| "input": [ | |
| "ClassName.class_var = new_value\n", | |
| "# sets the value of this class variable\n", | |
| "# and all class instances see the new value\n", | |
| "print(instance.class_var, other_instance.class_var)\n", | |
| "\n", | |
| "class_instance.set_class_var(new_value)\n", | |
| "# the class variable for this instance is now a new different object\n", | |
| "print(instance.class_var, other_instance.class_var)\n", | |
| "\n", | |
| "ClassName.class_var = new_value\n", | |
| "# this time only the other instance sees the new value\n", | |
| "# a new instance would also see the new_value\n", | |
| "print(instance.class_var, other_instance.class_var)" | |
| ], | |
| "language": "python", | |
| "metadata": {}, | |
| "outputs": [] | |
| }, | |
| { | |
| "cell_type": "code", | |
| "collapsed": false, | |
| "input": [ | |
| "class_instance.new_attribute = val # adds a new attribute to this class instance" | |
| ], | |
| "language": "python", | |
| "metadata": {}, | |
| "outputs": [] | |
| }, | |
| { | |
| "cell_type": "markdown", | |
| "metadata": {}, | |
| "source": [ | |
| "#####Error Handling" | |
| ] | |
| }, | |
| { | |
| "cell_type": "code", | |
| "collapsed": false, | |
| "input": [ | |
| "def function_name():\n", | |
| " try: \n", | |
| " ...\n", | |
| " except Exception as e: #catch exception\n", | |
| " print(e)\n", | |
| " else: \n", | |
| " ... # Exception didn't occur\n", | |
| " finally:\n", | |
| " ... # This code is always executed whether or not there was an exception" | |
| ], | |
| "language": "python", | |
| "metadata": {}, | |
| "outputs": [] | |
| }, | |
| { | |
| "cell_type": "markdown", | |
| "metadata": {}, | |
| "source": [ | |
| "#####File IO" | |
| ] | |
| }, | |
| { | |
| "cell_type": "code", | |
| "collapsed": false, | |
| "input": [ | |
| "# r removes the need to escape the slahes in the file path\n", | |
| "# w opens file for writing only\n", | |
| "\n", | |
| "file_name = open(r\"./file_name\", \"w\") # creates a file in the current directory\n", | |
| "file_name.write(\"Some String\")\n", | |
| "file_name.close()" | |
| ], | |
| "language": "python", | |
| "metadata": {}, | |
| "outputs": [] | |
| }, | |
| { | |
| "cell_type": "code", | |
| "collapsed": false, | |
| "input": [ | |
| "# no argument means open read only\n", | |
| "\n", | |
| "file_name = open(r\"./file_name\")\n", | |
| "s = file_name.read()\n", | |
| "file_name.close()\n", | |
| "\n", | |
| "print(s)" | |
| ], | |
| "language": "python", | |
| "metadata": {}, | |
| "outputs": [] | |
| }, | |
| { | |
| "cell_type": "markdown", | |
| "metadata": {}, | |
| "source": [ | |
| "<style>\n", | |
| "@font-face {\n", | |
| " font-family: \"Computer Modern\";\n", | |
| " src: url('http://9dbb143991406a7c655e-aa5fcb0a5a4ec34cff238a2d56ca4144.r56.cf5.rackcdn.com/cmunss.otf');\n", | |
| "}\n", | |
| "div.cell{\n", | |
| " width:800px;\n", | |
| " margin-left:16% !important;\n", | |
| " margin-right:auto;\n", | |
| "}\n", | |
| "h1 {\n", | |
| " font-family: Helvetica, serif;\n", | |
| "}\n", | |
| "h4{\n", | |
| " margin-top:12px;\n", | |
| " margin-bottom: 3px;\n", | |
| "}\n", | |
| "div.text_cell_render{\n", | |
| " font-family: Computer Modern, \"Helvetica Neue\", Arial, Helvetica, Geneva, sans-serif;\n", | |
| " line-height: 145%;\n", | |
| " font-size: 120%;\n", | |
| " width:800px;\n", | |
| " margin-left:auto;\n", | |
| " margin-right:auto;\n", | |
| "}\n", | |
| ".CodeMirror{\n", | |
| " font-family: \"Source Code Pro\", source-code-pro,Consolas, monospace;\n", | |
| "}\n", | |
| ".prompt{\n", | |
| " display: None;\n", | |
| "}\n", | |
| ".text_cell_render h5 {\n", | |
| " font-weight: 300;\n", | |
| " font-size: 16pt;\n", | |
| " color: #CF5300;\n", | |
| " font-style: italic;\n", | |
| " margin-bottom: .5em;\n", | |
| " margin-top: 0.5em;\n", | |
| " display: block;\n", | |
| "}\n", | |
| "\n", | |
| ".warning{\n", | |
| " color: rgb( 240, 20, 20 )\n", | |
| "}\n", | |
| "</style>" | |
| ] | |
| } | |
| ], | |
| "metadata": {} | |
| } | |
| ] | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment