{ "metadata": { "name": "", "signature": "sha256:627e257d195ea442481dfe5511719e160e6b29f79d680cbd6dd7e360c011c993" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Overview\n", "## Variables, Functions, Conditionals, Iteration\n", "\n", "Everything in Python is an object. Think of an object as a data structure that contains both data as well as functions. These objects can be variables, functions, and modules which are all objects. We can operate on this objects with what are called **operators** (e.g. addition, subtraction, concatenation or other operations), define/apply functions, test/apply for *conditionals* statements, (e.g. `if`, `else` statements) or iterate over the objects. \n", "\n", "Not all objects are required to have **attributes** and **methods** to operate on the objects in Python, but **everything is an object** (i.e. all objects can be assigned to a variable or passed as an argument to a function). A user can work with built-in defined classes of objects or can create new classes of objects. Using these objects, a user can perform operations on the objects by modifying / interacting with them. \n", "\n", "\n", "# Variables and Operators\n", "\n", "### Variables\n", "Variable names are case sensitive, can contain numbers and letters, can contain underscores, cannot begin with a number, cannot contain illegal characters and [cannot be one of the 31 keywords in Python](http://en.wikibooks.org/wiki/Think_Python/Variables,_expressions_and_statements#Variable_names_and_keywords): " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "> and, as, assert, break, class, continue, def, del, elif, else, except, \n", "exec, finally, for, from, global, if, import, in, is, lambda, not, or, \n", "pass, print, raise, return, try, while, with, yield" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Operators\n", "* Numeric operators are `+`, `-`, `*`, `/`, `**` (exponent), `%` (modulus if applied to integers)\n", "* String and list operators: `+` and `*` . \n", "* Assignment operator: `=`\n", "* The augmented assignment operator `+=` (or `-=`) can be used like n += x which is equal to n = n + x \n", "* Boolean relational operators: `==` (equal), `!=` (not equal), `>`, `<`, `>=` (greater than or equal to), `<=` (less than or equal to)\n", "\t* Boolean expressions will produce `True` or `False`\n", "* Logical operators: `and`, `or`, and `not`. e.g. x `>` 1 `and` x `<=` 5\n", "\t* Any nonzero number is interpreted as `True` \n", "\t* Values are evaluated left to right. e.g. 'yes' and 'no' will return 'no' because 'yes' is evaluated as True AND 'no' is evaluated as True.\n", "\t* `0`, `' '`, `[ ]`, `( )`, `{ }`, `None` are evaluated as False. \n", "\t* Order of operations for logic operators: `not`, `and`, `or`. Use parentheses `( )` to evaluate in order of preference.\n", "\n", "#### Format operators\n", "If % is applied to strings, this operator is the format operator. It tell Python how to format a list of values in a string. For example, \n", "\n", "* `%d` says to format the value as an integer\n", "* `%g` says to format the value as an float\n", "* `%s` says to format the value as an string" ] }, { "cell_type": "code", "collapsed": false, "input": [ "print 'In %d days I have eaten %g %s.' % (2, 3.5, 'lobsters')" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "In 2 days I have eaten 3.5 lobsters.\n" ] } ], "prompt_number": 1 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note, the list of strings after the `%` symbol must be equal to the number defined formats (e.g. number of of `%s`). " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Functions\n", "Python contains a small list of very useful built-in functions. All other functions need defined by the user or need to be imported from [modules](modules.html) which will be discussed in a little bit. For a more detailed list on the built-in functions in Python, see [Built-in Python Functions](https://docs.python.org/2/library/functions.html)\n", "\n", "## Really useful built-in functions: \n", "\n", "First, we'll discuss `type()`, `print()`, `dir()` and `str()`\n", "\n", "### type()\n", "\n", "The first function we'll discuss, `type()`, reports the type of any object, which is very useful when handling multiple data types (**remember**, everything in Python is an object). Here are some the mains types you will encounter: \n", "\n", "1. integer (`int`) \n", "2. floating-point (`float`)\n", "3. string (`str`)\n", "4. list (`list`)\n", "5. dictionary (`dict`)\n", "6. tuple (`tuple`)\n", "7. function (`function`)\n", "8. module (`module`)\n", "9. boolean (`bool`): e.g. True, False\n", "10. enumerate (`enumerate`)\n", "\n", "If we asked for the type of a string \"Go Red Sox!\"" ] }, { "cell_type": "code", "collapsed": false, "input": [ "type(\"Go Red Sox!\")" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 2, "text": [ "str" ] } ], "prompt_number": 2 }, { "cell_type": "markdown", "metadata": {}, "source": [ "This would return the `str` type. \n", "\n", "### print()\n", "The function `print` will accept an argument and print the argument to the screen. Print can be used in two ways: " ] }, { "cell_type": "code", "collapsed": false, "input": [ "print(\"Go Red Sox!\")\n", "print \"Wally the Green Monster\"" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Go Red Sox!\n", "Wally the Green Monster\n" ] } ], "prompt_number": 3 }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Note**: When writing a python script, you must use `print` to call the argument you want returned or the argument will be evaluated, but not printed.\n", "\n", "### dir()\n", "The next function we'll discuss is called `dir()` which takes in an object and returns all the methods of that object. If there is no argument provided, `dir()` returns a list of all the objects currently imported and available to work with. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here is an example that returns all the **methods** (you can think of them as functions of objects) that operate on [string](strings.html) objects: " ] }, { "cell_type": "code", "collapsed": false, "input": [ "dir(\"Three strikes and you're out!\") " ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 4, "text": [ "['__add__',\n", " '__class__',\n", " '__contains__',\n", " '__delattr__',\n", " '__doc__',\n", " '__eq__',\n", " '__format__',\n", " '__ge__',\n", " '__getattribute__',\n", " '__getitem__',\n", " '__getnewargs__',\n", " '__getslice__',\n", " '__gt__',\n", " '__hash__',\n", " '__init__',\n", " '__le__',\n", " '__len__',\n", " '__lt__',\n", " '__mod__',\n", " '__mul__',\n", " '__ne__',\n", " '__new__',\n", " '__reduce__',\n", " '__reduce_ex__',\n", " '__repr__',\n", " '__rmod__',\n", " '__rmul__',\n", " '__setattr__',\n", " '__sizeof__',\n", " '__str__',\n", " '__subclasshook__',\n", " '_formatter_field_name_split',\n", " '_formatter_parser',\n", " 'capitalize',\n", " 'center',\n", " 'count',\n", " 'decode',\n", " 'encode',\n", " 'endswith',\n", " 'expandtabs',\n", " 'find',\n", " 'format',\n", " 'index',\n", " 'isalnum',\n", " 'isalpha',\n", " 'isdigit',\n", " 'islower',\n", " 'isspace',\n", " 'istitle',\n", " 'isupper',\n", " 'join',\n", " 'ljust',\n", " 'lower',\n", " 'lstrip',\n", " 'partition',\n", " 'replace',\n", " 'rfind',\n", " 'rindex',\n", " 'rjust',\n", " 'rpartition',\n", " 'rsplit',\n", " 'rstrip',\n", " 'split',\n", " 'splitlines',\n", " 'startswith',\n", " 'strip',\n", " 'swapcase',\n", " 'title',\n", " 'translate',\n", " 'upper',\n", " 'zfill']" ] } ], "prompt_number": 4 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Besides strings, the function `dir()` also can be applied to any other type of object. For example, [modules](modules.html) are another type of object in Python which can be imported into Python to access functions in that module. Applying the `dir()` function to a module called `nameofmodule`, will return a list of methods (or functions) available in that particular module. \n", "\n", ">\tdir(nameofmodule)\n", "\n", "We'll discuss [modules](modules.html) in a little bit. I will note, above when you listed all the objects currently available to work with, one of the items was `__builtins__`, which is a special module that that is automatically imported on the startup. To find a list of all the built in functions in Python, you can use the module name `__builtins__`. " ] }, { "cell_type": "code", "collapsed": false, "input": [ "type(__builtins__)" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 5, "text": [ "module" ] } ], "prompt_number": 5 }, { "cell_type": "code", "collapsed": false, "input": [ "print dir(__builtins__)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '__IPYTHON__', '__IPYTHON__active', '__debug__', '__doc__', '__import__', '__name__', '__package__', 'abs', 'all', 'any', 'apply', 'basestring', 'bin', 'bool', 'buffer', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'cmp', 'coerce', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'dreload', 'enumerate', 'eval', 'execfile', 'file', 'filter', 'float', 'format', 'frozenset', 'get_ipython', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'long', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'range', 'raw_input', 'reduce', 'reload', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip']\n" ] } ], "prompt_number": 6 }, { "cell_type": "markdown", "metadata": {}, "source": [ "### str()\n", "Another powerful built-in function is called `str()` which takes in an input and coerces the input to a string. Every datatype (or object) can be coerced into a string, even modules! " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Other basic built-in Python functions\n", "\n", "Function name | Description | Example use\n", "--- | --- | ---- \n", "`callable()` | | \n", "`enumerate()` | accepts a string and returns an `enumerate` object type which is tuple containing a count (from start which defaults to 0) and the values obtained from iterating over string | `enumerate('myseq')`\n", "`int()` | converts floats and strings to integers (but chops off the fraction part and doesn't round) | `int(3.75)` returns 3\n", "`isinstance()` | verifies the type of of the argument | `isinstance(5, int)` returns `True`\n", "`range(n)` | accepts an integer and returns a list of integers from 0 to n-1 | `range(5)`\n", "`repr()` | accepts any input and returns the string representation of the object (helpful for debugging!) | `repr(range(5))`\n", "`getattr()` | accepts any object as input and returns any attribute of that object; technically works on any object, except tuples have no methods | \n", "`bin()` | accepts an integer and returns the binary representation | `bin(8)`\n", "\n", "\n", "### Defining new functions\n", "New functions can be defined using one of the 31 keywords in Python `def`. " ] }, { "cell_type": "code", "collapsed": false, "input": [ "def new_world(): \n", " return 'Hello world!'\n", " \n", "print new_world()" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Hello world!\n" ] } ], "prompt_number": 7 }, { "cell_type": "markdown", "metadata": {}, "source": [ "The first line of the function (the header) must start with `def`, the name of the function (which can contain underscores), parentheses (with any arguments inside of it) and a colon. The arguments can be specified in any order. \n", "\n", "The rest of the function (the body) always has an indentation of four spaces. If you define a function in the interactive mode, the interpreter will print ellipses (...) to let you know the function isn't complete. To complete the function, enter an empty line (not necessary in a script). \n", "\n", "To return a value from a function, use `return`. The function will immediately terminate and not run any code written past this point. " ] }, { "cell_type": "code", "collapsed": false, "input": [ "def squared(x):\n", " \"\"\" Return the square of a \n", " value \"\"\"\n", " return x ** 2\n", "\n", "print squared(4)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "16\n" ] } ], "prompt_number": 8 }, { "cell_type": "markdown", "metadata": {}, "source": [ "### The docstring\n", "\n", "When defining new functions, you can add a `docstring` (i.e. the documentation of function) at the beginning of the function that documents what the function does. The docstring is a triple quoted (multi-line) string. We highly recommend you to document the functions you define as good python coding practice. " ] }, { "cell_type": "code", "collapsed": false, "input": [ "def love_chocolate(N):\n", " \"\"\" A function to explain how much I love \n", " chocolate \"\"\"\n", " print 'I' + ' love '*N + ' chocolate'\n", "\n", "love_chocolate(3)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "I love love love chocolate\n" ] } ], "prompt_number": 9 }, { "cell_type": "markdown", "metadata": {}, "source": [ "To print the `docstring` from `love_chocolate()` function, use `__doc__` which is one of the functions **attributes**. " ] }, { "cell_type": "code", "collapsed": false, "input": [ "print \"Does squared have a docstring?\", squared.__doc__ != None\n", "print \"Does love_chocolate have a docstring?\", love_chocolate.__doc__ != None" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Does squared have a docstring? False\n", "Does love_chocolate have a docstring? True\n" ] } ], "prompt_number": 10 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Because everything in Python is an object, each object can have a set of built-in attributes and a set of built-in methods. All functions have a **built-in attribute** `__doc__` which returns the `docstring`. \n", "\n", "Variables can be defined over multiple lines with a backslash (\"\\\\\") as the line-continuation marker. \n", "\n", "The statement `raise` can be used in a function to raise an error message whenever the function fails to return a value. This statement will print a traceback and an error message. \n", "\n", "Variables written inside of a function are considered **local** variables and will disappear when the function ends. Variables written outside of a function are considered **global** variables and will remain after the function ends. To change the value of a global variable inside of a function, you must **declare** the global variable before you use it using the syntax `global` nameofvariable. The exception is if the global variable is mutable (e.g. lists, dictionaries), you can modify individual elements it without declaring it. \n", "\n", "Optional arguments can be provided to the functions where each optional argument has a specified default value. If another value is provided to the optional argument, it is over-written. " ] }, { "cell_type": "code", "collapsed": false, "input": [ "def squaredShifted(x, shift = 10):\n", " return shift + (x ** 2)\n", "\n", "squaredShifted(5, 20)" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 11, "text": [ "45" ] } ], "prompt_number": 11 }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Recursive functions\n", "Functions can call itself to allow for a recursive pattern. " ] }, { "cell_type": "code", "collapsed": false, "input": [ "def fact(n): \n", " if n ==0: \n", " return 1\n", " else: \n", " recurse = fact(n-1)\n", " result = recurse * n\n", " return result\n", " \n", "fact(4)" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 12, "text": [ "24" ] } ], "prompt_number": 12 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here the `fact()` function calculates the factorial of a given number in a recursive fashion by calling the `fact()` function within itself and returns the result. \n", "\n", "### Lambda functions\n", "\n", "Lambda functions are one-line functions. To define this function using the `lambda` keyword, you do not need to include the `return` argument. For example, we can re-write the `squared()` function above using the following syntax:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "f = lambda x: x**2\n", "\n", "f(3)" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 1, "text": [ "9" ] } ], "prompt_number": 1 }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Conditional statements\n", "Conditional statements allow us to check if a condition is true and then execute some portion of the function accordingly. \n", "\n", "### If else statements\n", "To define a statement with the `if` and `else` statement, we use a similar structure to defining functions by including a colon at the end of the header and four spaces indented for the body. " ] }, { "cell_type": "code", "collapsed": false, "input": [ "x = 1\n", "\n", "if x == 0: \n", " print 'x is equal to 0'\n", "else: \n", " print 'x is not equal to 0'" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "x is not equal to 0\n" ] } ], "prompt_number": 15 }, { "cell_type": "markdown", "metadata": {}, "source": [ "The body must contain at least one statement. The `pass` statement can be used in the body if no other statements are in the body. " ] }, { "cell_type": "code", "collapsed": false, "input": [ "if x == 0: \n", " pass # ignore zeros" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 16 }, { "cell_type": "markdown", "metadata": {}, "source": [ "If there are more than two possibilities for the condition you are testing, use `if`, `elif` (short for `else if`) and `else`. You can also nest conditionals, but they must be indented appropriately. " ] }, { "cell_type": "code", "collapsed": false, "input": [ "if x > 0: \n", " if x < 10: \n", " print 'x is greater than 0 and less than 10'\n", " elif x >= 10:\n", " print 'x is greater than 0 and greater than or equal to 10'" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "x is greater than 0 and less than 10\n" ] } ], "prompt_number": 17 }, { "cell_type": "markdown", "metadata": {}, "source": [ "A more succinct way of doing this is to use logical operators: " ] }, { "cell_type": "code", "collapsed": false, "input": [ "if x > 0 and x < 10: \n", " print 'x is bigger than 0 and less than 10'" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "x is bigger than 0 and less than 10\n" ] } ], "prompt_number": 18 }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Iteration \n", "Iterative loops can be written with the `for`, `while` and `break` statements. \n", "\n", "### For loops\n", "Defining a `for` loop is similar to defining a new function. The header ends with a colon and the body is indented with four spaces. The function `range(n)` takes in an integer n and creates a set of values from 0 to n - 1. `for` loops are not just for counters, but they can iterate through many types of objects such as strings, lists and dictionaries. " ] }, { "cell_type": "code", "collapsed": false, "input": [ "for i in range(4):\n", " print 'Hello world!'" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Hello world!\n", "Hello world!\n", "Hello world!\n", "Hello world!\n" ] } ], "prompt_number": 19 }, { "cell_type": "markdown", "metadata": {}, "source": [ "### while loops\n", "Defining a `while` loop is again similar to defining a `for` loop or new function. The header ends with a colon and the body is indented with four spaces" ] }, { "cell_type": "code", "collapsed": false, "input": [ "def countdown(n):\n", " while n > 0:\n", " print n\n", " n = n-1\n", " print 'Blastoff!'\n", " \n", "countdown(3)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "3\n", "2\n", "1\n", "Blastoff!\n" ] } ], "prompt_number": 20 }, { "cell_type": "markdown", "metadata": {}, "source": [ "To jump out of a loop, use `break`\n", "\n", "## Other useful information about Python\n", "* Comments in Python are with the pound symbol #\n", "* There are three types of errors: \n", "\t1. **syntax** errors = errors related to the structure of a program preventing the interpreter from executing a program. \n", "\t2. **runtime** errors = error does not appear until after the program has started running\n", "\t3. **semantic** errors = the program will execute successfully, but it will not do the intended thing. For example, if you type an integer with a leading zero, Python interprets it as binary. Another example of a semantic error is if you write the integer 1 million with commas between the zeros, Python interprets this as a comma-separated sequence of integers. \n", "\n", "\n", "\n", "\n", "\n", "\n", "\n" ] } ], "metadata": {} } ] }