Oct-16-2020, 05:59 PM
I like temperature conversion and I thought it would be fun to write a program in Python. I started with your program, but I didn't like that I had to enter temps in degrees Farenheight and I didn't like having to run the program over each time I wanted to enter a different temperature. I changed the program so the user can enter a temp using any of the units and use a more natural input like this:
Output:Enter Temperature followed by units: 32 F
0.0 C
150.0 D
32.0 F
273.15 K
0.0 N
491.67 Ra
0.0 Re
7.5 Ro
This was surprisingly easy in Python. For conversion I put all of my equations in a dictionary so I could look them up by unit. I chose Celsius as my standard unit and I have a dictionary of equations to convert from various units to Celsius, and another to convert from Celsius to various units. After that all I had to do was loop, split the input into parts, convert to Celsius, and convert from Celsius to all the other units.to_celsius = { 'C' : lambda C : C, 'D' : lambda D : 100 - D * 2 / 3, 'F' : lambda F : (F-32)/1.8, 'K' : lambda K : K - 273.15, 'N' : lambda N : N / 0.33, 'RA' : lambda RA: (RA - 491.67) / 1.8, 'RE' : lambda RE: RE * 1.25, 'RO' : lambda RO: (RO - 7.5) * 40 / 21 } from_celsius = { 'C' : lambda C: C, 'D' : lambda C: (100 - C) * 3 / 2, 'F' : lambda C: C * 1.8 + 32, 'K' : lambda C: C + 273.15, 'N' : lambda C: C * 0.33, 'RA' : lambda C: C * 1.8 + 491.67, 'RE' : lambda C: C / 1.25, 'RO' : lambda C: C * 21 / 40 + 7.5 } units = {'C':'Celsius', 'D':'Delisle', 'F':'Farenhieght', 'K':'Kelvin', 'N':'Newton', 'Ra': 'Rankine', 'Re':'Reamur', 'Ro':'Romer' } unit_str = ','.join([f'{sym}:{name}' for sym, name in units.items()]) print("Tempture Conversion\n___________________") print('Enter temeprature followed by units. For units use these codes:') print(unit_str) while True: inp = input('Enter Temperature followed by units: ').split() if len(inp) == 0: ## Nothing entered. Quit break; if len(inp) == 1: ## No units? Use Celsius as default inp.append('C') try: ## Convert to Celsius celsius = to_celsius[inp[1].upper()](float(inp[0])) ## Convert Celsius to all units for unit in units: print(from_celsius[unit.upper()](celsius), unit) ## Catch error and offer helpful suggestion except ValueError: print('Separate temperature and units by space') except KeyError: print('Use these temperature units\n', unit_str)It would be pretty easy to convert something like this to one of those programs where you have two boxes for values and two drop-down lists for selecting units.