调用特定函数

Calling a specific function

我正在尝试构建一个小型温度转换器。我想知道如何在开始时考虑用户输入和 运行 下面两个函数中的任何一个,而不是按顺序排列?

我应该在开始时使用 while() 循环吗?

感谢您的帮助。

user_input = input("This is a temperature converter. What do you want to convert:")

def convert_f():
    if user_input == "Celsius" or "C":
        print("To convert a temperature from Celsius to Fahrenheit. ")
        celsius = input("Celsius: ")
        convert_to_fahrenheit = float(celsius) * 9 / 5 + 3
        print(str(celsius), "degrees Celsius",  "is", float(convert_to_fahrenheit) , "degrees Fahrenheit")
convert_f()

def convert_c():
    if user_input == "Fahrenheit" or "F":
        print ("To convert a temperature from Fahrenheit to Celsius:")
        fahrenheit = input("Fahrenheit: ")
        convert_to_celsius: (float(fahrenheit) -32 * (5/9))
        print(str(fahrenheit), "degrees Fahrenheit", "is", float(convert_to_celsius), "degrees Celsius")
convert()

您可以在 while 循环中使用 if 检查输入。当您得到除“C”或“F”以外的其他内容时(例如用户简单地按下 Enter),您可以退出(打破循环)。

def convert_f():
    print("To convert a temperature from Celsius to Fahrenheit. ")
    celsius = input("Celsius: ")
    convert_to_fahrenheit = float(celsius) * 9 / 5 + 3
    print(str(celsius), "degrees Celsius", "is", float(convert_to_fahrenheit), "degrees Fahrenheit")


def convert_c():
    print("To convert a temperature from Fahrenheit to Celsius:")
    fahrenheit = input("Fahrenheit: ")
    convert_to_celsius = (float(fahrenheit) - 32 * (5 / 9))
    print(str(fahrenheit), "degrees Fahrenheit", "is", float(convert_to_celsius), "degrees Celsius")


while True:
    user_input = input("This is a temperature converter. What do you want to convert:")
    if user_input == "Celsius" or user_input == "C":
        convert_f()
    elif user_input == "Fahrenheit" or user_input == "F":
        convert_c()
    else:
        print("Invalid input. Exit.")
        break

我会重组此代码以减少重复。

IMO 应用程序的主要逻辑应与 I/O 部分(打印和请求输入)分开。

制作一些简单的方法来进行转换,并制作一些简单的方法来进行输入。制作简单的方法还可以让您分别对每个方法进行单元测试!

def convert_c_to_f(celsius):
    return (celsius * (9 / 5)) + 32

def convert_f_to_c(fahrenheit):
    return (fahrenheit - 32) * (5 / 9)

def ask_calc_type():
    while True:
        user_input = input(
            "This is a temperature converter. "
            "What do you want to convert:"
        )
        if user_input in ("Celsius", "C"):
            return "Celsius", "Fahrenheit"
        elif user_input in ("Fahrenheit" or "F"):
            return "Fahrenheit", "Celsius"
        else:
            print("Invalid choice, try again.")

def ask_number(from_type):
    while True:
        number = input(from_type + ":")
        try:
            return float(number)
        except:
            print("Invalid number, try again.")

现在你可以把这些放在一起了:

from_type, to_type = ask_calc_type()
request = ask_number(from_type)
if from_type == "Fahrenheit":
    response = convert_f_to_c(request)
else:
    response = convert_c_to_f(request)
print(f"{request} degrees {from_type} is {response} degrees {to_type}")