[Tutor] Please critique my temperature_conversion.py

Michael Janssen Janssen at rz.uni-frankfurt.de
Mon Jul 12 19:17:06 CEST 2004


On Mon, 12 Jul 2004, Bill Mill wrote:

> Dick, I rewrote your script with some of the changes we've suggested.
> Michael gives good advice on what to do. I tried to keep from
> inputting too much of my own style, and stick closely to your
> intentions.
> My only disagreement with Michael is that I think there should be two
> except clauses, because an IndexError occurs if the user enters a
> blank line.

Yes, beside my suggestion, to use only one try-except to verify input, you
can/must use any exception necessary to do the programm ;-)

OTOH I would prefer an if-test for input instead of catching an
IndexError: where ValueError is the "natural" thing to expect when
float'ing a non-number, IndexError isn't that straightforward for
non-input. You can even have a ValueError for non-input when you first do
the float-check. OTOOH it's completly okey to not test for empty string
but rather run into some error and catch it.

A more important remark: KeyboardInterrupt and EOFError should be
catched: At least on Unix or Linux you can interrupt a raw_input prompt
with ctrl-C (KeyboardInterrupt) or ctrl-D (EndOfFile). Since a python
traceback might nervous some users especially because it takes
some noticeable time to get printed out, you will hide it:

try:
    temperature = raw_input("Enter temperature: ")
except (KeyboardInterrupt, EOFError):
    # user nervously typing ctrl-C or ctrl-D
    sys.exit()

(note the syntax for catching two error-classes at once)


A last tip to beautify raw_input: Put

import readline # beautifies raw_input

somewhere at top of the script. raw_input will now make use of the
readline
module. The cursor keys and many keybindings are now operational.


regards
Michael


More information about the Tutor mailing list