1. Introduction to Python

MA 792K Spring 2011
Mark Lavin

2. 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

3. Python Is

  • Open source
  • General purpose
  • Object oriented
  • Dynamically typed
  • Garbage collected
  • Awesome [citation needed]

4. 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)

5. 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/

6. 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.

7. Who Uses Python?

Python wins the TIOBE Programming Language Award of 2010

Web companies: Google, Reddit and Caktus Consulting Group

Fortune 500: Honeywell, Phillips and Red Hat

Wall Street: SEC considered making Python a standard

Researchers and universities: NCSU, UNC and Duke

Other: Industrial Light & Magic

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

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

print "Hello, World!"

9. Beyond Hello World (fibonacci.py)

def fibonacci(n):
    if n <= 2:
        return 1
    else:
        return fibonacci(n - 1) + fibonacci(n - 2)

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

10. 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.

11. 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.

def my_long_function(arg1, arg2, optional_arg1="fizz",
    optional_arg2="buzz", optional_arg3="done"):
    pass
You can read the full style guide online

12. Zen of Python

import this

13. Declaring Functions

Functions are declared with the def keyword:

def my_function():
    pass

Arguments can given starting with required then optional:

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.

14. 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.

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'

15. Everything Is An Object

Everything has

  • An identity
  • A type
  • Some content
Great expanation of Python Object model:

16. Functions Can (And Do) Have Attributes

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.

17. Functions with Attributes (fibo2.py)

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

18. Functions Can Be Assigned to Variables

import math

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

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

19. Functions Can Be Changed at Runtime

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”.

20. What Do I Put in The Function?

Same operators you know and love from C:

# 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

21. Comparisons And Logic

Most will be familiar

# 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

22. Chaining Comparisons

x < 10 and x > 5

is the same as

5 < x < 10

23. Control Statements

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

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.

24. 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.

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

25. 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.

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

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

26. 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.

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

27. 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.

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

for name in ['Newton', 'x', 'Euler']:
    if 'x' in name:
        continue
    else:
        print name[0]

for name in []:
    print "Names were given."
else:
    print "No names were given."

29. 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.

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

30. Infinite Loop

Just like C you can create and infinite while loop.

while True:
    # Do something
    pass

31. 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.

32. 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.

# My Comment

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

33. 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.

34. 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.

if __name__ == "__main__":
    print "I am a script."
else:
    print "I am a module."

35. Imports

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

# 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')

36. 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.

37. Python Path

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

import sys
print sys.path

38. 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.

39. 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.

import math
print dir(math)
help(math)

40. Listing Built-ins

To list all built-in objects

import __builtin__
print dir(__builtin__)

41. Up Next

Build-in data types.