You could do it like this - but it is quite a rewrite.
You would need to add more conversion math for the missing cases (F to C, F to K etc.) to calculate the missing ones as well:
def convert(frm, to, value):
# you may want to make more smaller methods that do the calculation
# like def C2F(v): return (v * 9/5) + 32
# and call them inside your if statements
if frm == to:
print("Nothing to convert - same units.")
return value
if frm == "C" and to == "F":
print("Celsius to Fahrenheit")
return (value * 9/5) + 32
if frm == "C" and to == "K":
print("Celsius to Kelvin")
return value + 273.15
if frm == "C" and to == "R":
print("Celsius to Rankine")
return (value + 273.15) * 9 / 5
print(frm, to,"not supported.")
return "n/a"
def tryParseFloat(v):
"""Try parsing v as float, returns tuple of (bool, float).
If not a float, returns (False, None)"""
try:
return (True, float(v))
except:
return (False, None)
Main code:
allowed = {"K", "F", "C", "R"}
print(("Input two units (Celsius,Kelvin,Fahrenheit,Rankine) to convert from/to\n"
"and a value to convert (separated by spaces).\nEnter nothing to leave.\n"
"Example: K F 249 or Kelvin Rank 249\n\n"))
while True:
whatToDo = input("Your input: ").strip().upper()
if not whatToDo:
print("Bye.")
break
# exactly enough inputs?
wtd = whatToDo.split()
if len(wtd) != 3:
print("Wrong input.")
continue
# only care about the 1st letter of wtd[0] and [1]
if wtd[0][0] in allowed and wtd[1][0] in allowed:
frm = wtd[0][0]
to = wtd[1][0]
# only care about the value if it is a float
isFloat, value = tryParseFloat(wtd[2])
if isFloat:
print(value, frm, "is", convert(frm, to, value), to)
else:
print(wtd[2], " is invalid.") # not a number
else:
print("Invalid units - try again.") # not a known unit
Sample run & output:
Input two units (Celsius,Kelvin,Fahrenheit,Rankine) to convert from/to
and a value to convert (separated by spaces).
Enter nothing to leave.
Example: K F 249 or Kelvin Rank 249
Your input: f k 24
F K not supported.
24.0 F is n/a K
Your input: c f 100
Celsius to Fahrenheit
100.0 C is 212.0 F
Your input: c k 100
Celsius to Kelvin
100.0 C is 373.15 K
Your input: caesium kryptonite 100
Celsius to Kelvin
100.0 C is 373.15 K
Your input:
Bye.
To reduce the amount of code you might want to implement:
C2F, C2K, C2R, R2C, K2C, F2C
and for missing ones combine them (if you are ok with Is floating point math broken?) , f.e.:
def K2R(value):
return C2R(K2C(value)) # convert K to C and C to R for K2R