[Tutor] Please critique my temperature_conversion.py
Dick Moores
rdm at rcblue.com
Tue Jul 13 12:00:09 CEST 2004
Wow, is this a great list or what?
Thanks again, tutors. By golly, I think I've got it! I decided to use
Andrei's basic framework, and added some cool features suggested by others.
Thank you all for your kindness and patience.
Or if there's still room for improvement, please keep sending those cards
and letters!
(I have yet to dig into sys.argv yet. Soon)
BTW I'm using Windows, so it seems I can't use/don't have the readline
module. BTW2 Ctrl+Break doesn't do anything, on my computer.
Dick
#TempConverter.py
"""
temperature conversion: Fahrenheit <---> Celsius. User enters temperature
as a value (number) followed by a unit of either F or C.
The program uses the variable "temp_value"
to hold this original temperature value, and the variable "temp_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
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