如何向该代码添加多个输入.对于正确、不正确和无效的输出,我必须添加输入单元、输出单元和用户响应


temp = float(input("What is the temperature : "))
def C2F():
"Celsius to Fahrenheit"
f = (temp * 9/5) + 32
return (f)
def C2K():
"Celsius to Kelvin"
k = temp + 273.15
return (k)
def C2R():
"Celsius to Rankine"
r = (temp + 273.15) * 9 / 5
return (r)
print ("F = %.2f" % C2F())
print ("K = %.2f" % C2K())
print ("R = %.2f" % C2R())

如何向该代码添加多个输入。我必须添加正确、不正确和无效输出的输入单元、输出单元和用户响应

您可以这样做,但这相当于一次重写。

您需要为丢失的情况(F到C、F到K等(添加更多的转换数学,以计算丢失的情况:

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)

主要代码:

allowed = {"K", "F", "C", "R"}
print(("Input two units (Celsius,Kelvin,Fahrenheit,Rankine) to convert from/ton"
"and a value to convert (separated by spaces).nEnter nothing to leave.n"
"Example:    K F 249   or    Kelvin Rank 249nn"))
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

样本运行&输出:

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.

为了减少您可能想要实现的代码量:

C2F, C2K, C2R, R2C, K2C, F2C 

对于缺失的,将它们组合起来(如果你对浮点数学坏了吗?(,例如:

def K2R(value): 
return C2R(K2C(value)) # convert K to C and C to R for K2R

相关内容

最新更新