06.09.2021 Views

How to Think Like a Computer Scientist - Learning with Python, 2008a

How to Think Like a Computer Scientist - Learning with Python, 2008a

How to Think Like a Computer Scientist - Learning with Python, 2008a

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

228 Debugging<br />

A.3.2<br />

I’ve got a big hairy expression and it doesn’t do what<br />

Iexpect.<br />

Writing complex expressions is fine as long as they are readable, but they can be<br />

hard <strong>to</strong> debug. It is often a good idea <strong>to</strong> break a complex expression in<strong>to</strong> a series<br />

of assignments <strong>to</strong> temporary variables.<br />

For example:<br />

self.hands[i].addCard (self.hands[self.findNeighbor(i)].popCard())<br />

This can be rewritten as:<br />

neighbor = self.findNeighbor (i)<br />

pickedCard = self.hands[neighbor].popCard()<br />

self.hands[i].addCard (pickedCard)<br />

The explicit version is easier <strong>to</strong> read because the variable names provide additional<br />

documentation, and it is easier <strong>to</strong> debug because you can check the types of the<br />

intermediate variables and display their values.<br />

Another problem that can occur <strong>with</strong> big expressions is that the order of evaluation<br />

may not be what you expect. For example, if you are translating the expression<br />

in<strong>to</strong> <strong>Python</strong>, you might write:<br />

x<br />

2π<br />

y = x / 2 * math.pi<br />

That is not correct because multiplication and division have the same precedence<br />

and are evaluated from left <strong>to</strong> right. So this expression computes xπ/2.<br />

A good way <strong>to</strong> debug expressions is <strong>to</strong> add parentheses <strong>to</strong> make the order of<br />

evaluation explicit:<br />

y = x / (2 * math.pi)<br />

Whenever you are not sure of the order of evaluation, use parentheses. Not only<br />

will the program be correct (in the sense of doing what you intended), it will also<br />

be more readable for other people who haven’t memorized the rules of precedence.<br />

A.3.3<br />

I’ve got a function or method that doesn’t return<br />

what I expect.<br />

Ifyouhaveareturn statement <strong>with</strong> a complex expression, you don’t have a<br />

chance <strong>to</strong> print the return value before returning. Again, you can use a temporary<br />

variable. For example, instead of:

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!