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

Bill Mill bill.mill at gmail.com
Mon Jul 12 17:24:22 CEST 2004


On Mon, 12 Jul 2004 06:05:26 -0700, Dick Moores <rdm at rcblue.com> wrote:

Thanks, tutors, for all the criticism! I've been up all night (Pacific Time) trying to incorporate all of your advice into my script. Variable names, print formatting, exception catching, an outer while loop, eliminating the need for importing from string. Learned a lot.

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. Do note that the two exceptions can be handled on one line, since their result is the same, but that I separated them for clarity.

""" temperature_conversion.py temperature conversion: Fahrenheit <---> Celsius. User enters temperature as a number followed by a unit of either F or C. """

import sys

print """ temperature_conversion.py This program will convert Fahrenheit to Celsius or Celsius to Fahrenheit. Enter a number followed by F or C, such as 70F, 70 f, -12.47C, etc. To exit the program, simply enter "exit" """

while True: unit = "" converted_unit = "" temperature = "" while (unit != "F" and unit != "C"): input_string = "Enter temperature (70F, 70 F, -12.47C, etc.): " temperature = raw_input(input_string).strip().upper() if temperature == "EXIT": sys.exit(0) try: unit = (temperature[-1]) temperature = float(temperature[:-1]) # get just the number part except IndexError: print "please enter a temperature in the format <C|F>" except ValueError: print "please enter a temperature in the format <C|F>"

 if unit == "F":
     new_temp = 5/9. * (temperature - 32)
     print '%44.2fF is %.2fC' % (temperature, new_temp)
 else:
     new_temp = 9/5. * temperature + 32
     print '%44.2fC is %.2fF' % (temperature, new_temp)


More information about the Tutor mailing list