[Tutor] Re: Please critique my temperature_conversion.py (original) (raw)

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


Dick Moores <rdm 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).

ForC = ""

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

while (ForC != "F" and ForC != "C"): t0 = rawinput("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).

ForC = 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 ForC == "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")

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 :)

Yours,

Andrei



More information about the Tutor mailing list