Programming Digital Media

Beginning Python

You can type "python" at the command line, and you will see the "Python interpreter". You can type in Python code there in a manner similar to the shell. Python will "interpret" whatever you've typed:
    % python 
    Python 2.3 (#1, Sep 13 2003, 00:49:11)  
    [GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin 
    Type "help", "copyright", "credits" or "license" for more information. 
    >>> 1 + 2 
    3 
    >>> 4 * 99 
    396 
    >>> range(12) 
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] 
However, programs of any size at all are saved in a text file. You can then execute the Python code in the file by supplying it as an argument to the python command. For example, if you have a file called "myscript.py", that contained Python code, you would simply enter:
    python myscript.py 
For this first Python tutorial, try running Python with these four files:
  1. beginning_python_1.py
  2. beginning_python_2.py
  3. beginning_python_3.py
  4. beginning_python_4.py
Save the files to your ~/pdm/python directory using the appropriate browser command. Depending upon your browser, you may need to move it from the directory to which it was downloaded or redefine the download destination. For example, Safari defines the directory to which files are downloaded in its "Preferences" menu. For this tutorial, you could change your download directory to ~/pdm/python.

Once you have the scripts saved to your python directory, try running them. For example:

    python beginning_python_1.py 
Try making changes to the code and see what happens. Python is good about telling you the location of errors in a file, listing the line number where the error occurred.

beginning_python_1.py

# NAMING - Variables 
 
# The '#' character means "ignore everyting else on the line". 
# You can use it for comments. 
 
height = 71.9 
print height 
 
# You can print a list of things by separating them with commas. 
 
print "Height", height 
 
digits = [0,1,2,3,4,5,6,7,8,9] 
print 'Digits', digits  # The single quote works, too. 
# That was a comment at the end of the previous line. 
 
red =  1 
green = 2 
blue = 3 
color = [red, green, blue] 
print 'Color', color 
 
# You can do arithmetic, too: 
 
print 999 * 222 

beginning_python_2.py

# CHOICE - Conditionals 
 
# Conditionals do something based on the truth of an expression: 
 
# Since '=' means "assignment", use '==' to compare equality: 
 
if 1 == 1: 
    print 'One equals one.' 
 
# But in a script, of course, it won't be that trivial. 
 
a = 50 
if a < 10: 
    print 'Less than 10' 
else: 
    print 'Not less than 10' 
 
# You can keep testing by using "elif": 
 
 
a = 50 
 
if a < 10: 
    print 'Less than 10' 
elif a < 20: 
    print 'Less than 20' 
elif a < 30: 
    print 'Less than 30' 
else: 
    print '30 or greater' 
 
# Notice how it ends with a final else, so that no matter what "a" is, 
# one of the statements will be executed. 
 
# More than one statement can be part of an "if" structure by 
# indenting them the same amount.  The "if" structures can also be 
# "nested" -- an if structure inside another if structure: 
 
a = 0 
b = 0 
if a == b: 
    print 'a equals b' 
else: 
    if a < b: 
        print 'a less than b' 
        smaller = a 
    else: 
        print 'b less than a' 
        smaller = b 

beginning_python_3.py

# REPETITION - Loops 
 
# There are two basic types of loops: "for" loops (repeating for a 
# specific number of times) and "while" loops (repeating while a 
# condition is true). 
 
# The "range" function creates a list of numbers: 
 
print 'range', range(12) 
 
# Since you use the word "for", looping through a list is called a 
# "for" loop. 
 
for n in range(12):  # The variable "n" takes each value in turn. 
    print 'In the "for" loop; n is', n 
 
# You can have any number of statements inside the loop, all indented 
# the same amount: 
 
for n in range(5): 
    print 'Multiple statements in a for loop; this is loop', n 
    print n, 0 
    print n, 1 
    print n, 2 
    print n, 3 
 
# You can put a "for" loop inside another "for" loop.  You say that 
# the inner "for" loop is "nested".  Notice that the amount of 
# indentation is what creatings the nested loop.  The following is a 
# shorter way to do what the last loop did: 
 
index = 0 
for y in range(5):  # The variable "n" takes each value in turn. 
    for x in range(4): 
        print 'In the "nested" for loop:', index, x, y 
        index += 1 # This adds one to index 
 
# For "while" loops, some condition is tested: 
 
n = 1 
while n <= 10: 
    print 'In the "while" loop; n is', n 
    n = n + 1 
 
# You can often get the same results with "for" loops and "while" 
# loops.   For example, these are equivalent: 
 
# "For" version: 
for x in range(5): 
    print x 
 
# While version: 
x = 0 
while x < 5: 
    print x 
    x = x + 1 
 
# How you write a loop depends upon what makes most sense given what 
# your doing. In the previous case, the "for" loop is shorter, and 
# shorter is usually better.  (Don't, however, skimp on characters 
# when you create good variable names.)  For accessing all the pixel 
# coordinates in an image, loop statements like "for x in 
# range(p.width)" seem the most natural.  But if you were receiving 
# some trigger from a device in an installation, your loop would 
# probably be a "while something hasn't happened yet, keep checking". 

beginning_python_4.py

# GROUPING - Functions 
 
# A function has three parts: 
#   1. A name that you use when you "call" the function later 
#   2. The optional values you supply the function -- the "arguments" 
#   3. The result of the function 
 
# Here's a function that adds two numbers: 
 
def add(a, b): 
    return a + b 
 
# Notice to define a function, you say "def", then the name, then the 
# arguments as a list in parentheses. 
 
# In programming, it's handy to be able to represent things 
# symbolically.  I'll put symbols in all capital letters. Doing that, 
# I could say that a function structure looks like this: 
 
# def FUNCTION-NAME ( FUNCTION-ARGUMENTS ): 
#     FUNCTION-BODY 
 
# Depending upon how you think about things, this might be clearer or 
# more confusing.  The main idea is to see that there's a pattern, and 
# get a feeling for what has to be there all the time (like the Python 
# keyword "def" to mean "here comes a function definition") and things 
# that have be there, but can have different values (like the name of 
# the function, the symbol FUNCTION-NAME). 
 
# To use the function, you supply actual values: 
 
print 'Calling add with 2 and 3 returns', add(2, 3) 
 
# When you use a function ("call" the function), the values you supply 
# (like 2 and 3) become "bound" (assigned) to the symbols in the 
# function definition, but just for the body of the function.  So if I 
# have a function "multiply" that's defined like this... 
 
def multiply(a, b): 
    return a * b 
 
# ...and then I "call" it, like this... 
 
print multiply(34, 59) 
 
# ...then inside the function, a is equal to 34, and b is equal to 59. 
# The function call in that "print" statement is effectively doing this: 
 
a = 34 
b = 59 
print a * b 
 
# The reason that functions are handy, even though we can do the same 
# things without them, is that they can shorten the program when the 
# function is used repeatedly.  More importantly for our short 
# programs, we can give our functions names that describe what they 
# do.  So inside the function there can be all kinds of gritty 
# details, but the function, when it's called with its descriptive 
# name, is much clearer in what it's doing at that point in the 
# program. 
 
# Functions can have all the kinds of structures we've seen in them. 
# In this function, "numberbox", the loops are no different than what 
# we saw in the previous tutorial, they've just been "encapsulated" -- 
# bundled up -- in a nice container with a descriptive name: 
 
def numberbox(width, height): 
    n = 1 
    for x in range(width): 
        print 
        for y in range(height): 
            if n < 10: 
                print '', # The comma keeps it on one line. 
            print n,      
            n = n + 1 
    print  # This puts prints a blank line at the end. 
 
# So I can call the function with different arguments, but it isn't 
# any harder to use a big number than it is a small one.  This 
# wouldn't be true if I had to type every line out every time. 
 
numberbox(3,4) 
numberbox(4,5) 
numberbox(5,7) 
numberbox(7,10) 
 
print '\nAnother numberbox:'   # The '\n' means "newline" -- skip a line. 
 
def formatted_numberbox(width, height): 
    n = 1 
    for x in range(width): 
        print 
        for y in range(height): 
            print '%03d' % (n), 
            n = n + 1             
    print 
 
formatted_numberbox(2, 3) 
formatted_numberbox(4, 5) 
formatted_numberbox(9, 9) 
 
 
# When you define a function, you use it just like it was part of the 
# Python language.  One way of thinking about programming is that you 
# are adding to -- extending -- the base programming language to make 
# a new language that corresponds to what you're working on.