首页 > 解决方案 > 如何向此代码添加多个输入。我必须为正确、不正确和无效的输出添加输入单元、输出单元和 user_response

问题描述

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())

如何向此代码添加多个输入。我必须为正确、不正确和无效的输出添加输入单元、输出单元和 user_response

标签: python

解决方案


你可以这样做 - 但它是一个相当大的重写。

您还需要为缺失的情况(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/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

示例运行和输出:

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 

并且对于缺少的将它们组合起来(如果您对浮点数学是否损坏?),fe:

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

推荐阅读