调用特定函数



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

我应该在开头使用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}")

相关内容

  • 没有找到相关文章