[Tutor] Please critique my temperature_conversion.py
Dick Moores
rdm at rcblue.com
Tue Jul 13 16:33:53 CEST 2004
Oops! forgot one line. Left out this line:
temp_unit = temp_unit.upper()
(which enables user to enter lower-case c and f, as in 70f and 45c)
in this section:
# make sure we know the unit
temp_unit = temp_unit.upper()
if not (temp_unit in ['F', 'C']):
print "Unknown unit (%s)." % temp_unit
continue
Sorry.
So the script now is:
#temperature_conversion.py
"""
temperature conversion: Fahrenheit <---> Celsius. User enters temperature
as a number followed by a unit of either F or C.
The program uses the variable "number"
to hold this original number, and the variable "unit"
to hold the original F or the C.
"""
print """
TempConverter.py
TempConverter will convert Fahrenheit to Celsius or Celsius to
Fahrenheit.
Enter a temperature as a value followed by a unit (F or C),
such as 70F, 70 f, -12.47C, 34c, etc.
To exit program, enter exit, quit, stop, q, or x
"""
import sys, time
def exit():
print "Thank you for using TempConverter. TempConverter will now close"
time.sleep(1.1) # to provide the user with enough time to read the
message
while True:
temperature = ""
# for exiting via ^C or ^D
try:
temperature = raw_input('Temperature: ').strip()
except (TypeError, EOFError):
break
if temperature.lower() in ["exit", "quit", "stop", "q", "x"]:
break
# make sure there is input at all, i.e., catch ""; (" " already
stripped)
try:
temp_unit = temperature[-1]
temp_value = temperature[:-1]
except: # input is too short
print "Wrong input! Specify a value followed by a unit."
continue
# make sure we know the unit
temp_unit = temp_unit.upper()
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
#calculate new value now that sure have good value and unit
if temp_unit == "F":
new_value = 5/9. * (temp_value - 32)
print "%.2fF is %.2fC" % (temp_value, new_value)
else:
new_value = 9/5. * temp_value + 32
print "%.2fC is %.2fF" % (temp_value, new_value)
exit()
More information about the Tutor
mailing list