Welcome, guest | Sign In | My Account | Store | Cart

Code I got from a tutorial then edited . Changes fahrenheit to celsius , celsius to fahrenheit , fahrenheit to kelvin , and celsius to kelvin .

Python, 39 lines
 ``` 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:") ```

know 1 17 years, 4 months ago

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.

Raymond Hettinger 17 years, 4 months ago

Just for grins, here's an alternative approach the problem.

``````print 'Temperature converter (type  "quit" to exit)'

prompt = 'Enter a conversion such as "10 C to F" or "459 F to K":  '

while 1:
line = raw_input(prompt).upper()
if 'QUIT' in line:
break

t, fromto = None, []
for token in line.split(' '):
try:
t = float(token)
except ValueError:
pass
if token[:1] in 'CFK':
fromto.append(token[0])
if t is None or len(fromto) != 2:
print 'Unsuccessful parse.  Try again, using the format:  15 K to C'

# Convert to celsius
if fromto[0] == 'F':
t = (t - 32) * 5 / 9
elif fromto[0] == 'K':
t -= 273

# Convert from celsius
if fromto[1] == 'F':
t = t * 9 / 5 + 32
elif fromto[1] == 'K':
t += 273
print '--> %.1f %s' % (t, fromto[1])
``````
 Created by Riddle__ on Sat, 10 Jul 2004 (PSF)

### Tags

• (none)
▶ Show machine tags (4)

### Required Modules

• (none specified)