< Day Day Up > 


Python, like Perl, is an interpreted scripting language included with the system. To quote the website, Python is defined as

python, (Gr. Myth. An enormous serpent that lurked in the cave of Mount Parnassus and was slain by Apollo) 1. any of a genus of large, non-poisonous snakes of Asia, Africa and Australia that suffocate their prey to death. 2. popularly, any large snake that crushes its prey. 3. totally awesome, bitchin' language that will someday crush the $'s out of certain other so-called VHLL's ;-)

Python was built from scratch to be object-oriented and easy to write and read. Although it has the same features as other popular languages, its syntax is cleaner than most almost to the point of being scary. As such, it can take a little while for a long-time C or Perl developer to shake the uncontrollable feeling that somehow what they're writing in Python is wrong.

Languages such as Perl and even AppleScript have code structure based on explicitly starting and stopping code blocks with braces {}, tell application/end tell, and so on. In Python, the notion of a code block is still present, but rather than being explicitly stated with a keyword or symbol, it is implied by indentation.

Consider the following Perl code that prints the numbers between 1 and 10, and displays a special message when printing the number seven. The code is not indented because doing so is not required in Perl, and it is entirely at the whim of the developer to determine what proper indentation should be.

 #!/usr/bin/perl for ($count=1;$count<11;$count++) { print "The current value is $count\n"; if ($count==7) { print "I love the number 7!\n"; } } print "This program is finished." 

Rewritten in Python, this simple loop becomes

 for count in range(1,10):   print "The current value is",count   if count == 7:     print "I love the number seven!" print "This program is finished" 

Although there are minor differences in the looping and conditional syntax, the obvious difference is in the actual appearance of the code. We could have formatted the Perl code nicely to be indented and pretty to look at. Python, on the other hand, requires the given formatting. The indentation determines which lines of the program belong to a given code block. If lines are at the same level of indentation, they are part of the same block.

Your initial reaction might be to question why you would want to force yourself to write pretty code. The answer should be obvious to anyone who has ever tried to debug layers and layers of loops, conditionals, and so on, all embedded within one another without proper indentation.

Perhaps you've written a program but missed a closing brace somewhere? In Python, doing so is virtually impossible. You must program so that the visual representation of the program mirrors the intended execution. Python programs tend to be shorter, easier to read, and much easier to debug than languages that follow more traditional structures.

To create an executable Python script, you should include the Python interpreter in the first line (that is, #!/usr/bin/python) and make sure that the script has execute permissions by using chmod +x <script name>.


Python lines do not end in a semicolon like Perl, C, PHP, and so on. You can, however, use a semicolon in Python to include more than a single line of code on a single line in the program file, such as print "Hello"; print "Goodbye".

Variables and Data Types

Python's basic variable types are similar to Perl's, and, like Perl, they are case sensitive and do not require a type definition before their use. Unlike Perl, Python variables gain their meaning based on how they are used. A variable is considered numeric, for example, if you store a number in it, and is considered a string if it contains a string. These are the data types we'll be looking at in this introduction:

  • String A variable that contains a text/numeric or mixed value. The line myString="Macintosh G5" is an example of a string assignment in Python. The + symbol is the concatenation operator in Python.

  • Numeric An assignment such as processorG=5 creates a numeric variable with an integer value. By default, Python assumes that an operation performed on integers returns an integer, so you must explicitly use floating-point numbers where appropriate to avoid rounding errors. Python considers any value a floating-point number if it includes decimal places. For example, the assignment myVal=5/2 normally results in 2, whereas myVal=5/2.0 results in 2.5.

  • Lists A list is the Python equivalent of an array. A list is created by an assignment such as myList=['This","is","a","test."]. Individual elements are referenced by indexing into the list starting with 0. For example, myList[1] refers to the element "is" in the previously defined list. Unlike most array implementations, lists can be modified using insertion and deletion operators, which we'll discuss shortly. Python also supports an immutable list type called a tuple. Tuples are assigned just like a list, but use parentheses () rather than brackets.

  • Dictionaries A Python dictionary is the equivalent of a Perl associative array. For example, myDictionary={'Monday': "bad", 'Friday': "good"}. Here, the strings (keys) "Monday" and "Friday" are associated with the values "bad" and "good", respectively. You can refer to the elements of a dictionary by its keys. The element myDictionary["Friday"] returns "good".

  • Files Like a Perl filehandle, a Python file variable provides a reference to an active file for reading or writing. The statement $myFile=open("file.txt","r") opens the file file.txt for reading and allows file functions to be carried out through the variable $myFile.

Python is an object-oriented language, and, as such, accessing and manipulating data works a bit differently than in a traditional language. Object-oriented languages apply methods to objects instead of sending data to functions. For example, in Perl I might want to send a string to the uc() function to convert it to uppercase:

 $a="hello"; print uc($a); 

In Python, however, each of the basic data types is an object, and each has certain methods that that object can perform. String objects, for example, have an upper() method that converts them to uppercase. One invokes an object's method by using the syntax <object>.<method>. For example:

 a="hello" print a.upper() 

The difference becomes apparent when stringing together multiple methods or functions. To convert to uppercase and then back to lowercase in Perl, you'd embed a function call inside another function call:

 $a="hello' print lc(uc($a)); 

In Python, it is simply

 a="hello" print a.upper().lower() 

The a.upper() method returns another string object, which also has the lower() method and can subsequently be applied. Object-oriented programming has far more nuances than what we can show here. The ultimate goal of object-oriented programming is to create reusable objects that operate independently of the code that ties them together and that abstracts function from implementation.

Our goal is to give you enough information and incentive to get started using Python right away. If you like what you see, we hope that you will pursue learning the language further.

Input/Output Functions

While you take a few minutes to digest the object-oriented nature of Python, let's take a look at how you can get data into (and out of) Python. I've read dozens of language tutorials that spend far too much time discussing language intricacies rather than introducing basic I/O functions. Personally, I find that a language becomes useful as soon as you learn the basics for moving data in and out of a program.

Reading User Input

Basic user input is carried out through the raw_input(<prompt string>) function for strings, or input(<prompt string>) for integer and floating-point values. For example:

 myName=raw_input('What is your name? ') myAge=input('What is your age? ') print "Hello",myName+", you are",myAge*365,"days old." 

This code fragment inputs a name and an age, and then outputs a hello message along with the simple calculation of the person's age in days.

Although the raw_input function always returns a string, you can also use it with numeric values by coercing them to the proper type using the int() and float() functions. The second line of this sample, could be written

 myAge=float(raw_input('What is your age? ')) 


This example uses the float function wrapped around raw_input instead of using an object method. Certain functions (such as type coercion functions) are global and are not considered an object method. These functions are used just as in Perl.

Because float() and int() can be used to coerce strings to numbers, it stands to reason that numbers can be coerced to strings. This is performed by simply placing the numeric value within backticks (``). For example, to input myAge as a string, you could use the following:

 myAge=`input('What is your age? ')` 

Reading from Files

Another common form of input is a text file. To open a file for reading, use the syntax <filehandle>=open(<filename>,<file mode>). In the case of reading, the file mode is simply the string "r". After a file has been opened, you can use the object methods readline() and readlines() to return a single line of input or a list containing all the lines of input from the file, respectively. After file operations have been completed, the file should be closed with the object method close().

For example:

 myFile=open('MySpecialFile.txt','r') firstLine=myFile.readline() otherLines=myFile.readlines() myFile.close() 

This example opens the file MySpecialFile.txt for reading and creates the myFile object that can be used to refer to the file. The firstLine variable is used to store the first line of data from the file (retrieved via readline()), whereas otherLines contains a list (think "array") of the remaining lines in the file.

Creating Output

If you've been following along, you probably already know how to output to standard out in Python. The print statement is used to display information for the user. Unlike Perl's print, Python employs a "smart" print function that attempts to format output for you as cleanly as possible. For example, in Perl, you could write

 print "Hello, my name is ",$myName," and I am a Mac user.\n"; 

This would print a hello message with the user's name (spaces before and after) and end the message with a newline (\n). In Python, the equivalent statement is

 print "Hello, my name is",myName,"and I am a Mac user." 

Spaces are automatically inserted between strings in the print statement, and a newline is generated automatically at the end. If you want to suppress either of the spaces, you can replace the , with + the Python concatenation character. To suppress the newline, add a lone comma (,) to the end of the line.


You can use the same escaped characters such as \n, \r, \t, and so on that you use in Perl to refer to newlines, returns, and tabs among others.

File Output

Outputting data to a file requires, once again, the file-opening function <filehandle>=open (<filename>,<file mode>), this time used with a file mode of w for writing (and replacing any existing contents) or a for appending to a new or existing file.

The two object methods used to write information to a file are write(<string>) and writelines(<list>). The former writes a single string to the file, whereas the latter writes all the strings contained in the named list.

 myFile=open('MySpecialFile.txt','w') myFile.write("Hello World\n") myFile.close() 

This creates or replaces the file MySpecialFile.txt and writes the contents Hello World on a line in the file. Note that the write method includes a newline at the end. Unlike the print function, write requires you to explicitly format the outgoing data.

External Results

One nice feature of Perl is the ease with which you can execute external programs and incorporate their results in your script. You can do the same with Python using the commands.getoutput(<command to execute>) method. Before using it, however, you must import the necessary code simply import commands. For example:

 import commands myProcesses=commands.getoutput("ps ax") 

The resulting process list (generated by ps ax) is stored as a single string within the myProcesses variable.


Comparing values in Python is similar but not identical to Perl. Table 18.6 displays common Python expressions.

Table 18.6. Common Python Expressions

Expression Syntax


var1==var2, var1 is var2

Compares two values for equality.

var1!=var2, var1 is not var2

Compares two values for inequality.


Checks $var1 to see whether it is less than $var2.


Tests var1 to see whether it is a larger number than var2, or, when used with strings, whether var1 is before (based on ASCII value) var2.


Tests var1 to see whether it is greater than or equal to var2.


Compares var1 to see whether it is less than or equal to var2.


Parentheses can be used to group the elements of an expression together to force an evaluation order or provide clarity to the code.


Used to connect two expressions so that both must evaluate to true for the complete expression to be true.


Used to connect two expressions so that if either evaluates to true, the entire expression evaluates to true.


Used to logically negate an expression. If the expression previously evaluated to true, you can place a not in front of the expression to force it to evaluate false or vice versa.


A unique feature of Python is the capability to "slice" lists for the purpose of retrieving specific information, or inserting/deleting data. For example, assume that you have the following assignment:


You already know that myList[0] returns the first element of the list (that is, one). It is possible, however, to index into the list using a pair of values, such as myList[0:2]. In this case, the first two elements of the list (['one','two']) are returned. When using this format to dissect a portion of a list, the two numbers specified represent the first element to return and an element to serve as a boundary; the boundary element is not returned as part of the results, but the list element preceding it is.

As a shortcut for the start and boundary values in a slice, you can leave the first or last number of a slice empty. In the case of an empty initial value, 0 (the first element) is assumed. If the boundary value is left blank, the end of the list (including the final element) is assumed.

For example:

myList[1:3] returns ['two','three'].

myList[:2] returns ['one','two'].

myList[2:] returns ['three','four','five'].

myList[:] returns ['one','two','three','four','five'].

In addition to retrieving information, slicing can be used to delete and insert data in lists.

For example, given the previous list, we could change and insert into the second and third elements (['two','three']) new values (['two','two and a half','three','three and a half']) like this:

 myList[1:3]=['two','two and a half','three','three and a half'] 

The contents of myList are now

 ['one', 'two', 'two and a half', 'three', 'three and a half', 'four', 'five'] 

Similarly, you can delete elements from the middle of a list by assigning a slice to an empty list. For example, to delete the third, fourth, and fifth elements of the list, use


Common Functions and Object Methods

Being able to store and output information is useful, but the ability to manipulate it makes a computer a truly valuable tool. As you've read about Python data types and I/O, you've already seen a few methods used to for manipulating data, such as readlines and writelines for reading and writing to text files. Table 18.7 contains several more methods and functions, the data types they apply to, and what action they perform.

Table 18.7. Common Python Object Methods


Data Type




Returns the absolute value of the given number. Example: myABSVal=abs(-35)



Returns a string with the hex equivalent of the given number. Example: myHexVal=hex(10)



Rounds a given number to the specified number of digits (precision) after the decimal place. Example: MyRoundVal=round(10.05,1). Always returns a floating-point number.



Appends an element to the end of a list. Example: myList.append('six')



Removes an element from a list by its value. Example: myList.remove('six')



Sorts a list into alphabetical order. Example: myList.sort()



Removes and returns the last element in a list. If an index value is provided, it determines the number of elements returned and removed. Example: myList.pop()



Returns a count of the number of occurrences of a value within a list. Example: myG5Count=myList.count('G5')



Reverses the ordering of a list. Example: myList.reverse()



Returns the list element with the highest value. Example: myMaxValue=max(myList)



Returns the list element with the lowest value. Example: myMinValue=min(myList)



Capitalizes the first letter in a string and lowercases the rest. Example: myString.capitalize()

find(<search string>


Searches for a given search string and return the index [,<start position> value (position) where it starts. Returns -1 if no match is [,<end position>]]) found. If a start and end are given, the search takes place only between these index positions. Example: mySearchPos="Find the hidden word.".find('hidden')



Returns true if a string is alphanumeric. Example: myAlphaNumeric.isalnum()



Returns true if a string is entirely alphabetic. Example: myAlpha.isalpha()



Returns true if a string is entirely numeric. Example: myDigit.isdigit()



Returns true if all characters in a string are uppercase. Example: myUpper.isupper()



Returns true if all characters in a string are lowercase. Example: myLower.islower()



Converts the named list to a single string using the object string as the delimiter. Example: myJoinedString=",".join(myList)



Converts a string to uppercase. Example: myString.upper()



Converts a string to lowercase. Example: myString.lower()



Removes trailing whitespace from a string. Example: myString.rstrip()



Removes leading whitespace from a string. Example: myString.lstrip()



Returns a list of strings formed by splitting the object string on the given delimiter. Example: myDateElements="2003-08-25".split('-')

open(<filename>, <file mode>)


Returns a file handle after opening the given filename. The file mode can be r, w, or a for read, write, and append, respectively. Example: myFile=open('filename.txt','r')



Closes the file. Example: myFile.close()



Reads and returns a string containing a line of input from a file. If the optional byte parameter is specified, input is limited to that number of characters. Example: myInputLine=myFile. readline()



Reads and returns a list of input lines from a file. If the optional byte parameter is specified, input is limited to that number of characters. Example: myInputLines=myFile.readlines()



Writes the contents of the string to a file. Example: myFile.write('Hello\n')



Writes the contents of the list to a file. Example: myFile.writelines(myList)



Returns a list of values between the start and end values. Example: numberList=range(1,10)

Implementing Flow Control

Python's flow control is similar to other languages, with just a few syntactical differences. The biggest change from languages such as C, Perl, JavaScript, and so on is, once again, the use of indentation to denote code blocks. We'll use the same examples as in the preceding Perl introduction so that you can compare and contrast the source.


If a condition is met, a block of code is executed. If not, a different piece of programming is run. The syntax for this type of conditional statement is

 if <expression>:     <statements...> else:     <statements...> 

For example, to test whether the variable myComputer is set to the string "Mac OS X" and print Good Choice! if it is, you could write

 if myComputer is "Mac OS X":     print "Good Choice!" else:     print "Buy a Mac!" 


The while loop enables you to execute while a condition remains true. At the start of each loop, an expression is evaluated; if it returns true, the loop executes. If not, it exits. The syntax for a Perl while loop is

 while <expression>:     <statements> } 

For example, to monitor a process listing every 30 seconds to see whether the application Terminal is running, the following code fragment could be employed:

 import commands myProcesses=commands.getoutput("ps axg") while myProcesses.find('Terminal') is -1:     print "Terminal has not been detected."     commands.getoutput("sleep 30")     myProcesses=commands.getoutput("ps ax") print "The Terminal process is running." 

The output of the ps axg command is stored in myProcesses. This is then searched using find in the while loop. If the pattern Terminal is located, the loop exits, and the message The Terminal process is running. is displayed. If not, the script sleeps for 30 seconds and then tries again.


The Python for-next loop is slightly different from other implementations. Rather than loop through a series of numbers, it loops through the elements in a list. Frequently, these are numbers, but any list values will work. The range function is commonly used to provide a list of numbers. Using range(0,11), for example, generates the list [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10].

The syntax for a for-next loop is

 for <variable> in <list>:     <code block> 

For example, the following loop counts from 0 to 9:

 for count in range(0,10):     print "Count =",count 

Creating Functions

Functions (Python's version of subroutines) help modularize code by dividing it into smaller functional units. A Python function is started with the def keyword and the name the function should be called followed by a list of parameters it should receive within parentheses. The body of the function is an indented code block. For example, here is a simple function that prints Mac OS X:

 def printos():     print "Mac OS X" 

You can include a function anywhere in your source code and call it at any time by its defined name in this case, printos().

Functions can also be set up to receive values from the main program and return results. This example accepts two strings and concatenates them together:

 def concatenatestring(x,y):     return x+y 

To retrieve the concatenation of the strings "Mac" and "OS X", the subroutine would be addressed as

 myResult=concatenatestring("Mac","OS X") 

The incoming parameters ("Mac" and "OS X") are stored in the variables x and y and then returned in concatenated form (courtesy of the return keyword and the concatenation operator +).

Accessing Python Documentation

A great deal of documentation is provided with your Tiger Python distribution and is accessible through the pydoc utility. pydoc has a number of modes of operation, as shown in Table 18.8.

Table 18.8. Syntax for Using the pydoc Utility



-k <keyword>

Search the Python documentation for modules/classes that match a given keyword.

<name> ...

When used with just a single string argument, pydoc will lookup any documentation for classes, modules, functions, keywords, and so forth that match the value. If the value provided is keyword, modules, or topics, pydoc will list all items that fall within those categories.

-p <port number>

Using pydoc in this manner will start a web server that can be accessed at the given port number to display documentation graphically.


Uses a graphical interface to search documentation and also invokes the web server (much like -p). This function doesn't currently work correctly with Tiger.

-w <name> ...

Writes one or more HTML files containing the documentation of the named module.

For example, assume that you want to write a simple web server using Python (this is actually very easy!), you might want to search for HTTP within the Python modules by using the -k option:

 $ pydoc -k HTTP BaseHTTPServer - HTTP server base class. CGIHTTPServer - CGI-savvy HTTP Server. SimpleHTTPServer - Simple HTTP Server. httplib - HTTP/1.1 client library test.test_httplib 

pydoc returns a several results that match the HTTP keyword. To view the full documentation for a module, simply use pydoc <name>:

 $ pydoc SimpleHTTPServer Help on module SimpleHTTPServer: NAME     SimpleHTTPServer - Simple HTTP Server. FILE     /System/Library/Frameworks/Python.framework/Versions/2.3/lib/     python2.3/ DESCRIPTION     This module builds on BaseHTTPServer by implementing the standard GET     and HEAD requests in a fairly straightforward manner. CLASSES     BaseHTTPServer.BaseHTTPRequestHandler(SocketServer.StreamRequestHandler)         SimpleHTTPRequestHandler class SimpleHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler)      |  Simple HTTP request handler with GET and HEAD commands.      |       |  This serves files from the current directory and any of its      |  subdirectories.  It assumes that all files are plain text files      |  unless they have the extension ".html" in which case it assumes      |  they are HTML files.      |       |  The GET and HEAD requests are identical except that the HEAD      |  request omits the actual contents of the file.      |       |  Method resolution order:      |      SimpleHTTPRequestHandler      |      BaseHTTPServer.BaseHTTPRequestHandler      |      SocketServer.StreamRequestHandler      |      SocketServer.BaseRequestHandler ... 

A more user-friendly approach to browsing the Python documentation is to start the documentation server by using pydoc -p <port number>. You should use a number greater than 1024 to avoid trampling any system services. For example, to start a server on port 9000:

 $ pydoc -p 9000 pydoc server ready at http://localhost:9000/ 

After the server is started, simply point your web browser at the URL provided (http://localhost:<port number>) and you can click through all the available Python documentation within a graphical web interface, as shown in Figure 18.2.

Figure 18.2. Use pydoc -p <port> to start a personal Python documentation server.

Python Distributions

A source of confusion when learning Python on Mac OS X is the presence of a number of competing Python distributions and technologies. There is, of course, the primary Python distribution from, but a number of other Pythons are available that are either included on your system or can be installed.


The MacPython project works to bring native Mac OS X technologies to Python such as QuickTime, OpenGL, and so forth and even includes its own IDE and Package Manager for easily adding new features. Unfortunately, Apple chose not to include everything necessary to make MacPython fully useful, but an add-on fix package is available at to install the missing components.

MacPython is where you want to be if you are interested in building Tiger-specific applications written in Python. The drawback is that you limit yourself to the Mac OS X platform.


Also included in Tiger is the wxPython GUI toolkit ( wxPython provides a cross-platform GUI construction set that can be used to build applications across many platforms Linux, Windows, and so on. The wxWidgets library that the project is built on uses native Cocoa controls and widgets, so applications look native, but can be deployed on other platforms (assuming they've installed wxPython).


Apple apparently really likes to cover its bases because Tiger provides developer access to tkinter as well. tkinter is the most commonly used toolkit for building GUIs on top of Python scripts. Like wxPython, tkinter provides a cross-platform means of adding a native GUI onto a Python script. Whereas wxPython provides a more modern GUI toolkit, tkinter's use is widespread and more likely to be available on your deployment platforms.


Jython is a Java implementation of Python. Scripting languages are wonderful, but they don't package well for execution on other platforms. Providing a script to a user is much different from providing a double-clickable application.

For example, if you want to add GUI support to Python, you can use the proprietary MacPython Cocoa bindings or a third-party windowing/GUI toolkit that would need to be installed (if available) on each client computer. Jython eliminates the problem by providing a full implementation of Python within Java. Although there are a few minor incompatibilities, most Python code runs without any changes in Jython. Additionally, Jython provides easy access to Swing within Python, making it possible to author cross-platform GUI applications with ease.

Completed Jython applications can be compiled into .jar files for easy deployment on any Java-compatible system. For a free downloadable Jython installer, visit

Python Editors and IDEs

As with Perl, generic text editors such as AlphaX, BBEdit, and TextMate work well for Python. If, however, you're looking for a full Python development environment, a few solutions are available:

  • Wing IDE Currently the best solution for Mac OS X, the Wing IDE, shown in Figure 18.3, provides a full IDE for Python, but requires and operates within Apple's X11 implementation. If this doesn't deter you, it's well worth the $179 price for large scale development efforts. (

    Figure 18.3. The Wing IDE runs under X11 and provides a complete Python development environment.

  • PyOXIDE Early in development, PyOXIDE is an open source Cocoa-based Python IDE with a number of professional features and a promising future. (

  • PythonIDE Provided as part of the MacPython project, the PythonIDE is a complete development environment. This actually comes with Tiger, but doesn't include all the necessary packages to make it run. You can download an add-on package from to fix the broken installation.

Additional Python Information

Like the introduction to Perl, please realize that this should serve as only a basic primer to the Python language. The language is capable of far more than could be reasonably covered in a few introductory pages.

Thankfully, Python information is in abundance both in printed and electronic formats. If you don't mind reading through web pages (or printing off a few PDFs), you can find everything from beginner tutorials to complete references available online. Those looking for published products are also in luck; Python books are in ready supply. The following is a list of resources you might want to look into to learn more about the language and its capabilities:

  • The home of Python and a great source of Python documentation links and tutorials. This is the starting place for both beginners and experienced developers.

  • Instant Hacking: Learn How to Program with Python ( An excellent tutorial for getting up and running quickly with Python.

  • How to Think Like a Computer Scientist: Learning with Python ( An open source book that teaches the philosophy of programming through Python.

  • Practical Python, by Magnus Lie Hetland, ISBN: 1590590066 An excellent book by the author of the Instant Hacking tutorial. Practical Python is easy to read, understand, and apply.

     < Day Day Up > 

    Mac OS X Tiger Unleashed
    Mac OS X Tiger Unleashed
    ISBN: 0672327465
    EAN: 2147483647
    Year: 2005
    Pages: 251 © 2008-2017.
    If you may any questions please contact us: