[Tutor] Re: Please critique my temperature_conversion.py

Andrei project5 at redrival.net
Mon Jul 12 17:34:22 CEST 2004


Dick Moores <rdm <at> rcblue.com> writes:

> Exception handling is new to me, and I haven't succeeded here yet, as you 
> can see.

I think you've gone a bit overboard on the exception handling :). All you need
to check is three things:

0. there is input
1. the temperature unit is known
2. the input is a number

Raw outline, doesn't use your variable names since it's just for demonstration
purposes (continue breaks the current iteration and starts again at the top of
the loop):

while True:    
    temperature = raw_input('Temp:').strip()

    # make sure there is input at all
    try:
        temp_unit = temperature[-1].upper()
        temp_value = temperature[:-1].strip()
    except: # input is too short
        print "Wrong input! Specify a value followed by a unit."
        continue
    
    # make sure we know the unit
    if not (temp_unit in ['F', 'C']):
        print "Unknown unit (%s)." % temp_unit
        continue
    
    # make sure the value is a number
    try:
        temp_value = float(temp_value)
    except:
        print "The value you specified (%s) is not a number!" % temp_value
        continue
        
    print "OK"

    # Here comes the code which performs the conversion. You don't
    # have to do any  more try-excepts here, because you're sure
    # that your input is valid.
    
> And how to provide a smooth exit from the program? I experimented with 
> the exception that Ctrl+C raises, but doing this seems to make my 

Ctrl+Break should terminate it. Or you could build in an option to specify e.g.
"X" to exit. You then check if the (stripped and uppercased) input is X and if
that is the case, use break to terminate the loop (and therefore stop the
program). I'd recommend checking for more than one exit command (e.g. 'quit',
'exit', 'stop', 'q' and 'x') so the user can press whatever seems logical to her
and gets the desired result - the program terminates.

> No command line execution yet.

Hint: sys.argv. It's very handy for this type of programs.

Yours,

Andrei





More information about the Tutor mailing list