[Tutor] Re: Please critique my temperature_conversion.py

Andrei project5 at redrival.net
Mon Jul 12 08:42:10 CEST 2004


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

> from string import upper

Don't use the string module. Use string method instead, e.g. mystring.upper()
instead of string.upper(mystring).

> F_or_C = ""

As said by the previous poster, this isn't a very great name. I'd prefer
something like original_unit or from_unit.

> while (F_or_C != "F" and F_or_C != "C"):
>      t0 = raw_input("Enter temperature as 70F or 70 F or -12.47C: ")

I don't particulary like the name t0 neither. To me, this suggests "initial
time". Why not just call it e.g. temperature or even temp (although that
suggests something temporary).

>      F_or_C = upper(t0[-1]) # store the F or C and ensure upper case

If the user hits a space after the unit, this code won't recognise it. I'd
recommend stripping the input first.

>      t0 = t0[0:-1] #  strip entered temp of the F or C
>      t = t0 # get a string number to do the conversion calculation

Ah, but how do you know that it is a number? The user might have written
"kjanvkanvdf".

> if F_or_C == "F":
>      t = 5/9. * (float(t) - 32)

And here the lack of input validation will bite you. If t is now "kjanvkanvd",
the program will crash with a not particularly user-friendely error message.
It's better to validate the input using try-except and make sure that by the
time you end up in here, it's certainly a number.

>      t = round(t,2)
>      print (t0 + "F"), "is", (str(t) + "C")
<snip>

As already recommended, use format instrings instead. They're much clearer.

You didn't ask for them, but here are two other suggestions for improvements
anyway :)

- allow more than one conversion: run a potentially endless loop allowing the
user to convert a value and present her with a new prompt once the conversion is
done (or failed because of invalid input), so a new one can be done. A bit like
a very simple version of the Python interactive interpreter.

- add command line support, so it's possible to start e.g. "converttemp.py 32F"
and get the result in Celsius immediately, after which the program shuts itself
down.

Yours,

Andrei



More information about the Tutor mailing list