Introduction to Python
----------------------

| MA 792K Spring 2011
| Mark Lavin
| markdlavin@gmail.com


Course Info
----------------------

The book for this section of the course is Mark Pilgram's
"Dive into Python". The full book is available online at 
http://diveintopython.org/toc/index.html

My lecture notes (including source) and code examples are available
at https://bitbucket.org/mlavin/python-lectures/overview


.. figure:: /static/xkcd.png
    :height: 550px

    http://xkcd.com/353/


Python Is
----------------------

    - Open source 
    - General purpose
    - Object oriented
    - Dynamically typed
    - Garbage collected
    - Awesome :sup:`[citation needed]`


There Is More Than One Python
-------------------------------

Standard Python
    * Python 2.X - Last stable release 2.7.1
    * Python 3.X - Currently 3.1.3

Non-standard Python
    * Jython - Python implementation written in Java
    * IronPython - Python implementation written in .NET
    * Cython - Python extension for writing C/C++ extensions
    * PyPy - Python implementation written in Python (sort of)


Which Python Should I Use?
-------------------------------

Any of them. All of them!

I will cover the Python 2.X series targeting Python 2.6.

Python 2.6 currently has the best third party library support and 
well written Python 2.6 code will easily convert to Python 3.X.

Concepts you learn in Python 2.6 will translate well if you choose 
to use other even non-standard Python implementations.

Mark Pilgram has a new book called "Dive into Python 3" available at
http://diveintopython3.org/


Where can I get Python?
-------------------------------

You use Linux or a Mac then you probably already have it.

If you use Windows you can download an executable installer from Python.org.


Who Uses Python?
-------------------------------

`Python wins the TIOBE Programming Language Award of 2010 
<http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html?page=results_2010>`_

Web companies:
Google, Reddit and Caktus Consulting Group

Fortune 500:
Honeywell, Phillips and Red Hat

Wall Street:
`SEC considered making Python a standard 
<http://www.itworld.com/government/105031/will-wall-street-require-python>`_

Researchers and universities:
NCSU, UNC and Duke

Other:
Industrial Light & Magic

Read more: http://www.python.org/about/success/


Show Me Some Code! (hello.py)
-------------------------------

.. literalinclude:: /code/hello.py


Beyond Hello World (fibonacci.py)
--------------------------------------

.. literalinclude:: /code/fibonacci.py


Learn to Love Whitespace
-------------------------------

Python was created with the idea that most code will be read more times 
than it's written. With that in mind making code readable is important.

If you find you have deep nesting and your code starts to look odd 
with all the whitespace, then you probably need to rethink how you are writing it.


PEP 8
-------------------------------

The convention is to use 4 spaces per indention. NEVER mix spaces and tabs.

Suggested max line length is 79 characters. Backslash is a line continuation 
character but lines can also be extended with parentheses.

.. code-block:: python

    def my_long_function(arg1, arg2, optional_arg1="fizz",
        optional_arg2="buzz", optional_arg3="done"):
        pass

| You can read the full style guide online
| http://www.python.org/dev/peps/pep-0008/


Zen of Python
-------------------------------

.. code-block:: python

    import this


Declaring Functions
-------------------------------

Functions are declared with the def keyword:

.. code-block:: python

    def my_function():
        pass

Arguments can given starting with required then optional:

.. code-block:: python

    def short_name(first_name, last_name="Smith"):
        return "%s %s" % (first_name[0], last_name)

Notice that the arguments do not declare their type.


So, What's Your Type?
-------------------------------

Python is dynamically typed meaning you do not need to declare the types of 
your variables before using them. The variable type is determined when 
the program is executed.

Python is strongly typed meaning that type is enforced.

.. code-block:: python

    a = 1 # a is now an integer
    b = '2' # b is now a string
    c = a + b # this will fail
    c = a + int(b) # c is now an integer with a value 3
    c = str(a) + b # c is a string with value '12' 


Everything Is An Object
-------------------------------

Everything has 

    * An identity
    * A type
    * Some content


| Great expanation of Python Object model:
| http://www.effbot.org/zone/python-objects.htm


Functions Can (And Do) Have Attributes
----------------------------------------

.. code-block:: python

    import math
    print math.sqrt(4)
    print math.sqrt.__doc__


This particular attribute is call the doc string. You can use it to document your functions.


Functions with Attributes (fibo2.py)
----------------------------------------

Let's cache the fibonacci numbers on the function for later calls.


Functions Can Be Assigned to Variables
----------------------------------------

.. code-block:: python

    import math

    def do_math(f, x):
        print f(x)

    y = math.sqrt
    do_math(y, 10)
    y = math.log
    do_math(y, 10)


Functions Can Be Changed at Runtime
----------------------------------------

.. code-block:: python

    import math

    print math.log(10)

    def new_log(x):
        return 5

    math.log = new_log
    print math.log(10)

This is called "monkey patching" or "duck punching".


What Do I Put in The Function?
----------------------------------------

Same operators you know and love from C:

.. code-block:: python

    # add, subtract, multiply, divide
    a + b, a - b, a*b , a/b
    # exponentiation, floor divide,  modulo 
    a ** b,  a // b, a % b 
    # bitwise inverse, left bit shift, right bit shift
    ~a, a << b, a >> b
    # bitwise and, bitwise or, bitwise xor
    a & b, a | b, a ^ b


Comparisons And Logic
----------------------------------------

Most will be familiar

.. code-block:: python

    # less than, less equal, greater than, greater equal
    a < b, a <= b, a > b, a >= b
    # equal, not equal, object identity, object identity negation
    a == b, a != b, a is b, a is not b
    # collection membership, collection membership negation
    a in b, a not in b
    # logical and, logical or, logical negation
    a and b, a or b, not a


Chaining Comparisons
----------------------------------------

.. code-block:: python

    x < 10 and x > 5

is the same as

.. code-block:: python

    5 < x < 10


Control Statements
----------------------------------------

The basic flow control statements should also look familiar
from C though the syntax is slightly different.

.. code-block:: python
    
    if, else, for, while

The same as with functions there are no braces to define the logical
blocks. Instead everything is defined by the whitespace indention.


If
----------------------------------------

The ``if`` statement defines a control block which will only execute
when a logical statement is true. This can be paired with an ``else`` 
statement to define how to handle the false case. To avoid deep nesting 
you can also use ``elif`` statement.

.. code-block:: python

    if x > 100:
        print "That's a lot!"
    elif x > 10:
        print "That's ok."
    else:
        print "That's all you've got?"


For
----------------------------------------

The ``for`` statement is used to loop through any iterable collection.
This includes lists and strings. You can use the ``enumerate`` function to
add the current index.

.. code-block:: python

    for x in [1, 2, 3]:
        print x

    for i, c in enumerate("blip"):
        print "Character %s is %s" (i, c)


Range
----------------------------------------

``range`` and ``xrange`` allow you to generate a sequence of integers
between a particular range. They both default to start at zero and
increase by one. ``xrange`` is a back-port from Python 3.X and is slightly
better at managing memory.

.. code-block:: python

    for i in xrange(10):
        print i
    for i in xrange(1, 15):
        print i


Break/Continue/Else
----------------------------------------

The ``break`` statement can be used to end the execution of a ``for`` loop early.
The ``continue`` statement can be used to skip to next item in the loop without
executing the rest of the loop. The ``else`` statement can be used with a for loop
to execute in the case where the collection is empty.


Break/Continue/Else Example (breakdance.py)
-----------------------------------------------

.. literalinclude:: /code/breakdance.py
    :lines: 1-11


While
----------------------------------------

In addition to the ``for`` loop there is also the ``while`` loop. The ``while`` loop
will continue until a particular logical statement is false.

.. code-block:: python

    x = 10
    while x > 5:
        x -= 1


Infinite Loop
----------------------------------------

Just like C you can create and infinite ``while`` loop.

.. code-block:: python

    while True:
        # Do something
        pass

Pass
----------------------------------------

``pass`` is a special keyword in Python that does nothing. It can be used to fill 
a control block or a function or a class definition.


Comments
----------------------------------------

Python comments are denoted with the # character. While not techinally a comment
you can also use triple quoted strings as a multi-line comment. This is the style
used to define doc strings previously discussed.

.. code-block:: python
    
    # My Comment

    """
    This is a longer comment.
    Blah blah blah.
    Though technically it's a string literal.
    """


Building Python Modules
----------------------------------------

Python modules are collections of Python statements. They stored in text files with the
.py extension. The module name is the same as the file name without the extension.


Modules as Scripts
----------------------------------------

When you pass a module to the interpreter such as ``python hello.py`` the module name
changes from ``hello`` to ``__main__``. You can use this fact to handle the case where
the module is executed differently than when the module is imported.

.. literalinclude:: /code/script.py


Imports
----------------------------------------

We've already seen some import statements but there are three styles of Python imports.

.. code-block:: python

    # Add a reference to the module
    import X
    # Creates references to all public objects in X
    from X import *
    # Creates refernces to the names a, b, c
    from X import a, b, c
    # Add a reference to the module
    X = __import__('X')


Which Import to Use?
----------------------------------------

Use ``import`` unless you know exactly what you want. Avoid ``from X import *`` because
it makes your code less readable since it isn't clear where certain names and objects
are defined.


Python Path
----------------------------------------

Where does Python look for modules to import? The Python path.

.. code-block:: python

    import sys
    print sys.path


What Happens on Import?
----------------------------------------

When Python imports a module, it first checks the module registry (sys.modules) 
to see if the module is already imported. If that’s the case, Python uses the existing module object as is.

Otherwise, Python does something like this:

1. Create a new, empty module object (this is essentially a dictionary)
2. Insert that module object in the sys.modules dictionary
3. Load the module code object (if necessary, compile the module first)
4. Execute the module code object in the new module’s namespace. All variables assigned by the code will be available via the module object.


Listing Module Data
----------------------------------------

To see all the objects (remember everything is an object) defined in a module
you can use the built-in ``dir`` function. For help you can call ``help``.

.. code-block:: python

    import math
    print dir(math)
    help(math)


Listing Built-ins
----------------------------------------

To list all built-in objects

.. code-block:: python

    import __builtin__
    print dir(__builtin__)


Up Next
----------------------------------------

Build-in data types.


.. header:: 

   MA792K Spring 2011 Lecture 1

.. footer:: 

   © Mark Lavin 2011
