Being a PUGnosed PIGgie Local User Groups

Python user groups gather in what computer nerds call meatspace in cities throughout the world. Such groups welcome beginners and provide demonstrations, lectures, and time for questions and socializing. (Sometimes you get free food, too ) The groups often have the acronym PIG (Python Interest Group) or PUG (Python User Group) in their names. A list of local user groups can be found on the Python Wiki here The Python Wiki might not be up-to-date, so if you don't see a group in your area, be...

Comparison operators

Comparison operators test whether something is equal to and or greater than or less than something else. Table 10-1 lists the comparison operators. Table 10-1 Python's Comparison Operators Table 10-1 Python's Comparison Operators REMEMBER All comparison operators have the same priority. Statements with multiple comparison operators are evaluated from left to right. REMEMBER All comparison operators have the same priority. Statements with multiple comparison operators are evaluated from left to...

Converting a sequence

To create a dict from a list or tuple and an optional mapping value, use the fromkeys() method. (This works in Python 2.3 or later.) The items in the sequence become the keys, and the mapping value (None by default) is used for the values. In this example, each item in the list is turned into a key and given the value 'breakfast' > > > mylist 'spam', 'eggs', 'orange juice' > > > print dict.fromkeys(mylist, breakfast) 'eggs' 'breakfast', 'orange juice' 'breakfast', 'spam' 'breakfast'...

Finding whats in standard modules

Python comes with a library of standard modules. Many of these modules are covered in Part IV and elsewhere in this book. Tip If you want to find out the gory details about any of the standard modules that we don't cover, see the Python Library Reference at http www.python.org (it's usually also included when you install Python instructions for installing Python documentation are in Appendix A). The built-in function dir() returns a sorted list of the names a module defines. To use it, type dir...

How local and global names work with references

Because Python searches for names first locally and then globally, you can reference a global name inside the function assuming the function doesn't contain a local name that's the same as the global name. This example program (we call it brightdog.py) and Figure 11-2 show that a function can access the name a_book defined outside the function a book man's best friend print outside of a dog, a book is, a book def a bright dog() print inside of THIS dog, a book is still, a book a bright dog()...

Didnt think they would do that

When you write programs for other people to use, especially programs that ask users to provide input of some kind, users may give your program input it doesn't expect. For example, if your program asks the user to input a number, she might accidentally type a letter instead. If your code is set up to work only with a number, this input would cause your code to fail. Proper exception handling catches input of the wrong type, prints a friendly reminder about what input to use, and lets the user...

Ickling Your Data And Relishing the Outcome

The pickle and cPickle modules let you store data between runs of a program, the way a word processor allows you to save formatted documents and edit them later even if you quit the program. This is called pickling because it's a way of preserving your data. TECHNICAL Storing a Python object in a file makes it a persistent object. You STUFF could write your own code to store and read Python objects, but if your data includes complex objects, it's easier to use pickling because it automatically...

Incorrect logic for Boolean expressions

To get the scoop on correct use of Boolean expressions in your programs, see Chapters 3 and 10. The best way to find out about common bugs (other than writing your own programs) is to look at the bugs other people make. The comp.lang.python newsgroup or the Python tutor mailing list are good resources. (See Chapter 22 to find out how to access these resources.) The same errors come up over and over, and you'll soon be able to recognize them on sight. Tip For helpful debugging tips, see...

It pays to be conventional

Python programmers have conventions for how they add comments to their programs. The conventions make the comments and code easier to read by other programmers. Here are some of the guidelines for comments Keep lines to fewer than 80 characters. (This convention applies to the whole program, not just the comments.) Indent comments the same amount the code is indented. For more information on indenting, see Deciphering Code Blocks, later in this chapter. Use inline comments (comments that come...

Lets pause for a moment

The time module's sieep() method is useful for programs that need built-in pauses. (Quiz shows, anyone ) The sleep() method pauses the execution of a program for a specified number of seconds. The following example uses the sieep() method The following example uses the sieep() method This is the result of running the example code This is the result of running the example code

On the line beneath your class definition header indent four spaces

Many classes require you to pass arguments when you make instances from them. Creating attributes for these parameters in the_init_() method lets other methods To write an_init_() method that includes parameter attributes, follow these steps 1. On the line beneath your class definition header, indent four spaces and type this 3. On the same line, type a comma and the name of a parameter, like this 5. Repeat Step 2 for each parameter you want to include. 6. Type an end parenthesis and a colon )...

On the next line type four spaces and then type the action you want repeated like this

While number of bottles > 0 4. print number of bottles, bottles of beer on the wall If you add more lines, be sure to indent them. Tip A while loop is useful in a program that waits for user input. The program in Listing 10-3 reports on the results of several coin tosses. The while loop checks whether the user has asked to quit the program. Listing 10-3 Coin toss program_ print Now tossing a coin while userinput.lower() q flip random.choice( 'heads', 'tails' ) print heads the number of heads...

Open a command window

O If you're using Mac OS X, open the Terminal application and select File 1 New Shell. o If you're using Windows, open the Command Prompt window. o If you're using UNIX, either open a new shell window or just type in your existing shell window. When Python opens, you see the text shown in Figure 2-1. When Python's interactive mode starts up, it tells you what version is running, the date the version was released, and a few hints about what to do next. Then it displays the Python prompt > >...

Processing special characters in a URL

To process special characters (such as a space or tilde) in a URL, use the urllib module's quote_plus() function. Warning Although the functions quote() and unquote() are similar to quote_plus(), we recommend using quote_plus() to avoid problems with URLs that contain + and space characters. The quote_plus() function has a required argument and an optional argument. Required argument The quote_plus() function requires a URL string (or part of a URL) as an argument and does the following...

Python and earlier dont support newstyle classes at all and newstyle classes work differently in than in and later

So if you use new-style classes, your code might have problems running in Python 2.2 and earlier. We focus on classic classes in this book because they're still the default and will remain the default until Python 3.0 in addition, the vast majority of code in existence (including the Python library) still uses classic classes. Before Python 2.2, data types could be created only by using the C programming language, and classes couldn't inherit from built-in or third-party data types. If you...

Random Access Reference at httpwwwwikipythonorg

The Web page http www.wiki.python.org contains links to two Wikis the Python Wiki (for Python) and the Jython Wiki. (Jython is Python for Java.) A Wiki is a collection of Web pages that anyone can edit. Wikis usually make heavy use of hyperlinks, and you gather information by jumping from one page to another as you find linked topics that interest you. The front page for the Python Wiki contains a list of starting points for jumping in. This includes a Code page that lists bits of useful code...

Run the altered script by typing code like this into your browser replace hostnamecgibin with the path to your cgibin

If the diagnostic text and the text after the in the above line of code appears in the Web browser, then the script is installed correctly, and any problems you're having are probably with your script's code. Tip If the cgi.test() code doesn't work, then the script probably isn't installed correctly. Go back to Installing a script and setting permissions, earlier in this chapter. You might need to ask your Web hosting company for the path of your cgi-bin directory.

Run the cgipy module by typing code like this into your browser replacing hostnamecgibin with the path to your cgibin

The results show whether the script is installed in the correct directory If the directory is correct, some diagnostic text, including the text after the in the above line of code, appears in the Web browser. If you see a 404 error or a message that the page can't be found, then the scripts are installed in the wrong directory. You might get a different error if the script is in the right directory but installed incorrectly.

Seeing whats inside Python objects

The dir() function returns an alphabetized list of an object's attributes, such as functions or methods, constants, and the name of the object. Here's how to use the dir() function To see the names in the current namespace, type dir(). If you type dir() immediately after starting Python's interactive mode, you will see something like this To see all the attributes (named items) belonging to an object, type dir(name of object). For example > > > dir(ArithmeticError) To see the attributes...

Technicalprogramming to the max

Smart programmers have come up with a variety of methods for writing better programs. Many of those methods are combined under the umbrella of Extreme Programming(XP). (Some programmers have always wanted to be as cool as skateboarders. Maybe using a term like this helps. Or maybe not.) The idea behind XP is simple If a programming method is a Good Idea, take it to the max For example, one of the best ways of getting bugs out of a program is to have another programmer review the code. Well, why...

Technicalstatements and expressions Seeing the difference

Python code consists of statements and expressions. Knowing these terms isn't essential to writing basic code, but sometimes they help you to understand an error in your code (for example, you can't use a statement where an expression is required). A literal is a chunk of text in a Python program that specifies the value for one of the basic Python data types (such as a string or number). When you run your program, Python creates an object with the literal's value. A statement is like a command...

Technicalwhat is Unicode and why do we care about it

When people started teaching computers how to talk, the computer geeks came up with a system called ASCII (American Standard Code for Information Interchange). ASCII characters are encoded by using 7 bits of information, which allows for only 128 (0-127) characters. That wasn't enough for non-English languages, accented characters, and other common symbols. Enter Unicode. Unicode will eventually be able to encode every character set, including those for non-European languages, alphabets used by...

The function is designed to work in more than one way depending on which arguments are passed

For example, the open() function opens a file for reading by default. If you want to open a file for writing, you need to specify a mode argument, 'w' . When adding default-value parameters to function definitions, follow these rules 1. Type any parameters that won't have keywords first. Parameters without keywords are called positional. 2. Type keyword arguments in the form keyword value. The following function definition has one required (positional) parameter (ingredient) and two...

The Mothership httpwwwpythonorg

The Python mothership on the Web is docked at http www.python.org. If you have questions about Python, you should go here first. It includes the latest versions of Python for download, along with documentation, FAQs, introductions, tutorials, a Wiki (an encyclopedia-type structure that anyone can edit), mailing list archives, announcements, links to third-party modules, and more. A search box is available on most of the main pages of http www.python.org. If you want to search specific parts of...

The story of Python

Guido van Rossum created Python and is affectionately bestowed with the title Benevolent Dictator For Life by the Python community. In the late 1980s, Guido liked features of several programming languages, but none of them had all the features he wanted. Specifically, he wanted a language that had the following features Scripting language A script is a program that controls other programs. Scripting languages are good for quick development and prototyping because they're good at passing...

To run the script from the command line type python i followed by the name of the script including the py suffix

When you run the script, Python executes its code and then enters interactive mode (you can tell because you see the > > > prompt). testing how scripts and interactive mode communicate The names that are part of tinyscript.py are now available in interactive mode. To test this, type dir() and print the value of any of your script's names.

Tools of the re module

The following regex functions and methods are the most useful. findall() findall() returns a list of all the occurrences of a regex in a string. It also takes an optional flag argument (Table 18-3 lists the flags). Tip finditer() does the same thing as findall() but returns an iterator object rather than a list. To find a single occurrence of a regex at the start of a string, use match() match() takes a string and an optional flag as arguments (Table 18-3 lists the flags). o A Matchobject...

Tutorpythonorg and helppythonorg

The Tutor mailing list is for beginning and intermediate Python programmers to ask and answer each other's questions. Its Web page is here You can post a message to it by sending e-mail to tutor python.org. We recommend that if you post a message, you also subscribe to the list You can do so via a form on the above Web page. Tutor mailing list archives are at When you use the search box on the Python home page, you get results from the Tutor Archives as well as from other pages on the site. If...

Updating a dictionary

To replace the values in a dictionary with new values, use the update() method. The new key value pairs can come from either another dictionary (or other mapping object) or an iterable of key value pairs (such as a list of two- item tuples). TECHNICAL The iterable (key value) option requires Python 2.4 or later. STUFF You can also replace values by using keyword arguments, as in this example > > > rooms '12A' 'argument clinic', 12 'abuse' > > > rooms.update(A14 'hit on the head...

Use append to add an item to the end of the queue

In the following example, we create an empty list and then append six callers to it In the following example, we create an empty list and then append six callers to it Use pop(0) in a while loop to retrieve an item from the front of the queue, Warning To avoid performance problems, don't use pop(0) with a large list (more Warning To avoid performance problems, don't use pop(0) with a large list (more

Using interactive mode as a calculator

The Python interpreter can be used like a calculator. If you just want to do simple calculations, you can type numbers and operators and press Return to see the result, as in the following example Warning Don't use an equals sign ( ) when doing calculations like these. In Python, an equals sign gives a name to a value. If you use to try to get the result of a calculation, Python gives you an error message File < stdin> , line 1 1 + 3 * 2 + 2 You can also use names to do math in the Python...

What spiderpy doesnt have

The spider.py program works as-is, but it's missing a few elements that are necessary to make it a fully functional Python program that follows the conventions of good programming Docstrings for each function and class method. Error checking. For example, if you try to run the program from the command line without specifying a URL, the program fails messily. Here's what happens Traceback (most recent call File spider.py, line 91, IndexError list index out of Why are we showing a program without...

Tuple unpacking

Unpacking a tuple means giving a different name to each element of the tuple. Tuple unpacking is useful because many functions in Python, such as the zip function described in the previous Building lists incrementally section, return tuples. With tuple unpacking, you can easily get at the individual items in these tuples. To unpack a tuple, just assign multiple names on a single line. Put the names you want to unpack into on the left side of the assignment statement and put the tuple on the...

Getting Close Enough with difflib

People often make mistakes when entering text. The difflib module gives you a way to find strings that are close but not exact matches to a given string gt gt gt right 'The quick brown fox' gt gt gt wrong 'THe quack brown fix' gt gt gt matcher difflib.SequenceMatcher None, right, wrong The ratio method returns a floating point number between 0 and 1 that indicates how close the match is. Higher numbers indicate a closer match. A match higher than 0.6 is usually considered good maybe not by...

Debugging in IDLE

When you run code in IDLE's interactive mode, it informs you of errors the same way you've seen when using interactive mode in a Terminal or shell window. When you run code from the text editor, IDLE also informs you of errors. Depending on the kind of error and on your version of IDLE, the error message appears in a dialog box or in the Python Shell window. You can use the IDLE debugger to step through your program in various ways and display the values of names. The IDLE debugger is shown in...