Python in One Easy Lesson

This is a one-hour introduction to Python used for Stanford's CS107.
This material should work as an introduction for any experienced programmer.
We'll look at some core Python features and get a feel for how it compares to other languages.
For a longer introduction to Python by the same author with videos and exercises, see
Google's Python Class.
For online practice problems, see codingbat.com

Python is a popular open source, cross-platform language in the "dynamic language" niche, like Javascript, Ruby, Lisp, and Perl. See python.org home for docs, code, tutorials, etc.

Unlike C/C++, Python defers almost everything until runtime. Variables and functions do not have compile time types. Values at runtime are tagged with their type: int, string, ... . Variables just point to value at runtime, and each value's type is used at runtime to resolve what the run should do. For example here's a variable x pointing first to an int, then to a string. The variable x does not have a type, but whatever value it points to does have a type.

This is how Python works, in contrast to the C/C++ style of knowing the type of every variable and using that for compile time code generation. Python does not generate code in that way at compile time. For example, consider this code fragment:

x = x + x

In Python, x could be an int, or a string, or who knows what. Without that type information, code generation cannot work the way it does in C/C++.
Instead, the Python interpreter looks at the types present in each bit of code in the moment at run time. This makes Python slower than C/C++, but also very flexible, and in any case it is missing both the advantages and disadvantages of a compile time type system. A Just In Time compiler (JIT) plays on this boundary -- working at run time, on the fly, to compile native code for code fragments. Since it's run time, the JIT can know the types stored in certain variables, etc. Java JIT technology is very mature. Python JITs are just getting started (see PyPy project).

Interpreter and Variables

You can run the Python interpreter and type code directly in to it -- a good way to try little experiments. The interpreter runs a read-eval-print loop with whatever you type. Don't need to declare variables and they do not have a fixed type. Reading from a variable that does not have a value is a runtime error. Python has a garbage collector (GC) provides automatic deallocation of unused memory.

Strings

Strings are delimited with ' or " or """, and are immutable. The len() function used to get length of all sorts of python types. Call len(s) to get length of string and s[0] accesses individual chars. There is no separate char type -- just a string length 1.
See the many string methods at: http://docs.python.org/library/stdtypes.html#string-methods

Lists [ ], For Loop

List literals are enclosed in square brackets. Lists can contain any type of value. Use the len() function and [] to access elements (same as string). The .append() method appends an element to a list. See the official docs for the many available list methods: http://docs.python.org/tutorial/datastructures.htmlImportant foreach syntax on lists: for var in list:

Program syntax, if/else, Indentation

Below is the complete text of a cat.py file which prints out text file contents.

#!/usr/bin/python -tt
"""
cat.py -- just a little example python program
showing some common syntax. This program works.
nick.parlante@cs.stanford.edu
-tt flag above detects space/tab indent problems
"""
# sys is one of many available modules of library code, import to use.
# sys.argv is the list of command line arguments.
import sys
# defines a global variable
a = 123
# defines a 'cat' function which takes a filename
def cat(filename):
"""Given filename, print its text contents."""
print filename, '======='
f = open(filename, 'r')
for line in f: # goes through a text file line by line
print line, # trailing comma inhibits the ending print-newline
# alternative, read the whole file into a single string:
# text = f.read()
f.close()
def main():
# sys.argv contains command line arguments.
# This assigns a list of all but the first arg into a local 'args' var.
args = sys.argv[1:]
# important syntax -- loop of variable 'filename' over the args list.
for filename in args:
# detect scary filenames: if/else and/or/not
if filename == 'voldemort' or filename == 'vader':
print 'this file is very worrying'
cat(filemane, 123, bad_variable)
# important point: errors in above line only caught if it is run
else:
# regular case
cat(filename)
print 'all done' # this print is outside the loop, due to its indentation
# Standard boilerplate at end of file to call main() function.
if __name__ == '__main__':
main()

The indention of each line controls whether it is within a loop, if statement, etc. -- there are no { } to define blocks of code.
This use of indentation in Python is unusual, but it's logical and you get used to it. It's best to not use
tab characters within your Python code; just use spaces.

Dict { } Hash Table

The built-in dict (i.e. hash-table) type uses { } for literals. Use dict[key-val] both to read and set entries in the dict. Build up a dict, starting it as {}, then assigning in the desired values.

Sorting

The sorted(list) function takes in a list (or any linear sequence) and returns a new, sorted list of those elements. The optional reverse=True argument takes care of the common case where you want the sort reversed.

Custom sorting

Python includes a new way to do custom sorting, and it's better than the old 2-argument cmp function way. Supply a function of *one argument*, a 'key' function, which computes a "proxy" value for each element in the original list, making a list of proxy values. The sorting algorithm then uses the proxy values for comparison, but does the sort on the original list.

This code uses the built-in len function as the key function, and so sorts the strings by length:

The key function can be defined using an ordinary def: so you can define a function that extracts the data you want to be used to guide the sort of the original list. Suppose you want to sort a bunch of strings by their 2nd letter.

Lambda (optional)

A lambda, in many languages, is a syntax for defining a function inline instead of in a separate def.
The Python syntax is: lambda var: expressionHere's the above example written using lambda to define the key function inline:

print sorted(words, key=lambda word: word[1])

Custom Sort + Dict Example

For the following example, a "tuple" works like a little list, but it is written within ( ) instead of [ ]. Suppose we have a dict of city->zip data and we want to print it out in order by zip. This can be done with custom sorting. The .items() on the dict returns the whole dict contents as a list of tuples. Each tuple is length 2, containing one key/value (city/zip) pair, like this:

We want to sort the items list into increasing order by zip code. Write a little function to use as the key function, taking in one element in the list (a tuple length 2), and returning the part we want to use in the sort (just the zip code):

Python Development Advice

The two most common newbie bugs are forgetting the ":" for an if or loop and having uneven indentation within an if or loop (this gets a compile-time error).

Since there's no separate compile step, it's very easy to make a little edit and then run to see how it works. Take advantage of that quickness in your development style. In particular, you can print out whatever your data structure is at some point and then sys.exit(0) to end the program. Keep doing that until it looks right, then work on getting the next data structure 8 lines lower to look right. Printing the concrete state of your data structure makes it easier to see the next step.

Good variable names are especially helpful in Python code, since they are the only thing there to remind you of what you have -- a string, a list, a dict. It's easy to lose track, so use variable names to keep things straight.