• No results found

Pseudo-coding your thoughts

In document 0471778648 (Page 68-71)

One way to design your program is to create an outline of sorts, using what is called pseudo-code. You write a sketch of what your program will do, using the structures you'll need to use when you write the program (such as class and function definitions and if

statements), but you don't bother with the syntax details necessary to write working code.

TECHNICAL STUFF

Pseudo-code tends to resemble real Python programs, so it takes less effort to convert pseudo-code into working Python code. When the pseudo-coding process is finished, the details are easy to fill in.

Here's an example of pseudo-code that almost works as Python code:

if today == sunday:

full_backup() else:

incremental_backup()

Debugging

A bug is a mistake in a piece of software that causes it to work improperly or to return incorrect results.

TECHNICAL

STUFF Teaching an old bug new tricks

This use of the word bug was already common before software was invented—for example, Thomas Edison used it in 1878 to describe problems with his inventions. Some people will tell you, though, that the term derives from an incident in which an actual insect was found to be causing glitches inside an early computer in 1947.

Although bug is older than writing programs, debugging has been an inherent part of writing software since people started writing

software. One of the first computer scientists, Maurice Wilkes, is reputed to have said, "I can remember the exact instant when I realized that a large part of my life from then on was going to be spent in finding mistakes in my own programs."

The Zen of Python

Writing a complex program is something like designing a building. The architect's constraints include time, money, good taste, and the structural limits of the materials.

Programming also requires balancing multiple needs—often including time, money, the feature requests of multiple groups of people, and the availability of sufficient quantities of caffeine.

Pythonista Tim Peters contributed 19 guidelines for good Python code. We consider them the best distillation of the Python philosophy of programming. They're on this Web page:

http://www.python.org/doc/humor/#zen

These are design principles, not rules to be followed blindly. They're meant to encourage you to think. In some cases the principles may appear contradictory. That's a reflection of the fact that programming sometimes requires balancing conflicting requirements. It's like the old saying: "Good, fast, cheap—pick any two." The principles can help you decide how to prioritize these requirements.

The principles were originally written to guide the development of Python itself, but they also apply to writing your own programs. That's how we discuss them here.

Some of the most important guidelines are these:

Explicit is better than implicit. Good code is as self-explanatory as possible:

Use names that explain the purpose of the objects they represent.

Include comments in your code when it isn't obvious what a particular line or block does.

Avoid hidden effects. (For example, printing to the screen shouldn't erase your hard drive.)

Readability counts. A good program is easy for a human to read and understand. If two blocks of code produce the same result, consider using the one that's easier to read.

(Sometimes cryptic code runs faster, but speed isn't the primary goal of most Python programming.)

Errors should never pass silently. If you write code that doesn't alert the user of errors, the errors might cause the program to give incorrect results:

Build explicit error checking into your code.

Write code to catch any errors that you haven't thought of.

Report errors to the user of your program.

There should be one—and preferably only one—obvious way to do it. This guideline ("There's only one way," for short) is the most popular among people in the Python community. This is partly in response to the motto of Perl programmers, which is,

"There's More Than One Way To Do It." The Python community creates and popularizes standard coding idioms(preferred ways of performing certain tasks). Using standard idioms saves time because the code is already mostly written; you just plug in your data and variables. Python For Dummies includes many standard idioms to get you started.

Typing import this at the Python prompt in Python 2.1.2 or higher will print the entire list:

>>> import this

The Zen of Python, by Tim Peters Beautiful is better than ugly.

Explicit is better than implicit.

Simple is better than complex.

Complex is better than complicated.

Flat is better than nested.

Sparse is better than dense.

Readability counts.

Special cases aren't special enough to break the rules.

Although practicality beats purity.

Errors should never pass silently.

Unless explicitly silenced.

In the face of ambiguity, refuse the temptation to guess.

There should be one-- and preferably only one --obvious way to do it.

Although that way may not be obvious at first unless you're Dutch

Now is better than never.

Although never is often better than special enough to *right* now.

If the implementation is hard to explain, it's a bad idea.

If the implementation is easy to explain, it may be a good idea.

Namespaces are one honking great idea let's do more of those!

Most computer programs have bugs. When you discover problems with the way your program works or the results it gives, you debug to

Find the source of the mistake.

Fix the lines of code causing the problem.

As you get comfortable with programming and Python, you get a better sense for how the computer "thinks," which helps you figure out bugs more quickly. You'll become familiar with common causes for common problems like:

Syntax errors. Missing punctuation is the most common syntax mistake. For example, if you try to create a string but forget a quotation mark, you'll get an error like this:

>>> mystring = "No! Not the Knights who say 'Ni'!

File "<stdin>", line 1

mystring = "No! Not the Knights who say 'Ni'!

^

SyntaxError: EOL while scanning single-quoted string

Tip You'll have fewer syntax errors in your programs if you use a Python- aware

text editor that prints different syntax in different colors.

Tips for avoiding common syntax errors can be found throughout Python for Dummies.

Misspelled names. If you name an object and then misspell the name when you refer to it later, you'll get an error. For example:

>>> lumberjack = "I'm OK"

>>> print lumbrejack

Traceback (most recent call last):

File "<stdin>", line 1, in ?

NameError: name 'lumbrejack' is not defined

Using the wrong types of values. For example, if you have a number in string format (perhaps from the raw_input() function, which converts the input into a string) and you try to do arithmetic with it, you'll get a result you didn't expect, like this:

>>> x = raw_input("Enter a number: ")

Enter a number: 45

>>> x * 2

'4545'

Creating infinite loops. If you create a loop by using a condition that never terminates, your program will try to run forever, like the brooms that the Sorcerer's Apprentice creates:

sorcerer = "asleep"

def make_broom():

print "another broom!"

while sorcerer == "asleep":

make_broom()

Tip Chapter 10 shows you how to create loops that you can control.

Trying to open files that don't exist or are empty, for example:

>>> myfile = open('foo.doc')

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

IOError: [Errno 2] No such file or directory: 'foo.

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 "Debugging Strategies," later in this chapter.

In document 0471778648 (Page 68-71)