Code I got from a tutorial then edited . Changes fahrenheit to celsius , celsius to fahrenheit , fahrenheit to kelvin , and celsius to kelvin .
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | # Temp changer by Josh Bailey (Riddle)
# July 10 '04
def print_options():
print "Options:"
print " 'p' print options"
print " 'c' convert celsius to fahrenheit"
print " 'f' convert fahrenheit to celsius"
print " 'k' convert celsius to kelvin"
print " 'x' convert fahrenheit to kelvin"
print " 'q' quit the program"
def celsius_to_fahrenheit(c_temp):
return (9.0/5.0*c_temp+32)
def fahrenheit_to_celsius(f_temp):
return (f_temp - 32.0)*5.0/9.0
def celsius_to_kelvin(k_temp):
return (temp + 273)
def fahrenheit_to_kelvin(k_temp2):
return (temp -32.0)*5.0/9.0 + 273
choice = "p"
while choice != "q":
if choice == "c":
temp = input("Celsius temp:")
print "Fahrenheit:",celsius_to_fahrenheit(temp)
elif choice == "f":
temp = input("Fahrenheit temp:")
print "Celsius:",fahrenheit_to_celsius(temp)
elif choice == "k":
temp = input ("Celsius temp:")
print "Kelvin:",celsius_to_kelvin(temp)
elif choice == "x":
temp = input ("Fahrenheit temp:")
print "Kelvin:",fahrenheit_to_kelvin(temp)
elif choice != "quit":
print_options()
choice = raw_input("option:")
|
use of globals. In celsius_to_kelvin() and fahrenheit_to_kelvin() the global variable 'temp' is used in the return calculations instead of the local method parameters k_temp and k_temp2 respectively. This may lead to confusion. Also, in fahrenheit_to_kelvin() there is no need to do the fahr2Celcius math again. Simply return fahrenheit_to_celcius(k_temp2) + 273. This seems cleaner.
Just for grins, here's an alternative approach the problem.