15.04.2013 Views

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

eturn retval<br />

Upon running our new code, we obtain the following (different) messages when providing improper input<br />

to safe_float(), even if both exceptions are managed by the same handler:<br />

>>> safe_float('xyz')<br />

'invalid literal for float(): xyz'<br />

>>> safe_float({})<br />

'object can't be converted to float'<br />

10.3.7. Using Our Wrapped Function in an Application<br />

We will now feature safe_float() in a mini application that takes a credit card transaction data file<br />

(carddata.txt) and reads in all transactions, including explanatory strings. Here are the contents of our<br />

example carddata.txt file:<br />

% cat carddata.txt<br />

# carddata.txt<br />

previous balance<br />

25<br />

debits<br />

21.64<br />

541.24<br />

25<br />

credits<br />

-25<br />

-541.24<br />

finance charge/late fees<br />

7.30<br />

5<br />

Our program, cardrun.py, is given in Example 10.1.<br />

Example 10.1. Credit Card Transactions (cardrun.py)<br />

We use safe_float() to process a set of credit card transactions given in a file and read in as<br />

strings. A log file tracks the processing.<br />

1 #!/usr/bin/env python<br />

2<br />

3 def safe_float(obj):<br />

4 'safe version of float()'<br />

5 try:<br />

6 retval = float(obj)<br />

7 except (ValueError, TypeError), diag:<br />

8 retval = str(diag)<br />

9 return retval<br />

10<br />

11 def main():<br />

12 'handles all the data processing'

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

Saved successfully!

Ooh no, something went wrong!