[英]How can I make a def function with my "if" statements?
我們被要求創建一個名為溫度轉換的函數,它接受一個稱為溫度的整數參數、一個稱為輸入單元的輔助字符串參數和一個稱為輸出單元的第三個字符串參數。 輸入單位指定溫度值的單位。 此函數應將溫度值轉換並返回目標單位中指定的單位。 兩個單位參數都應為“C”、“K”或“F”之一。
我想出了一堆if
語句並且它有效,但我無法創建有效的函數。
input_unit, target_unit = input("Input the temperature and the unit to convert it to: [e.g. 45c f > valid Units: C,K,F: ").split()
degree = int(input_unit[:-1])
i_unit = input_unit[-1].upper()
o_unit = target_unit.upper()
if i_unit == "C" and o_unit == "F":
result = int((1.8 * degree) + 32)
print("{:0.2f}°{} ⇒ {:0.2f}°{}".format(degree,i_unit,result,o_unit))
elif i_unit == "C" and o_unit == "K":
result = int(degree + 273.15)
print("{:0.2f}°{} ⇒ {:0.2f}°{}".format(degree,i_unit,result,o_unit))
elif i_unit == "F" and o_unit == "K":
result = int(((degree * 1.8) +32)+ 273.15)
print("{:0.2f}°{} ⇒ {:0.2f}°{}".format(degree,i_unit,result,o_unit))
elif i_unit == "F" and o_unit == "C":
result = int((degree - 32) / 1.8)
print("{:0.2f}°{} ⇒ {:0.2f}°{}".format(degree,i_unit,result,o_unit))
elif i_unit == "K" and o_unit == "C":
result = int(degree - 273.15)
print("{:0.2f}°{} ⇒ {:0.2f}°{}".format(degree,i_unit,result,o_unit))
elif i_unit == "K" and o_unit == "F":
result = int(((degree - 273.15) - 32) / 1.8)
print("{:0.2f}°{} ⇒ {:0.2f}°{}".format(degree,i_unit,result,o_unit))
else:
while True:
input_unit, target_unit = input("Input the temperature and the unit to convert it to?: ").split()
if input_unit[-1].upper() != "C" or target_unit.upper() != "F":
print("You enterd an invalid unit. Please enter again: ")
你可以使用這個功能
def convert(degree, i_unit, o_unit):
if i_unit == "C" and o_unit == "F":
result = int((1.8 * degree) + 32)
print("{:0.2f}°{} ⇒ {:0.2f}°{}".format(degree,i_unit,result,o_unit))
elif i_unit == "C" and o_unit == "K":
result = int(degree + 273.15)
print("{:0.2f}°{} ⇒ {:0.2f}°{}".format(degree,i_unit,result,o_unit))
elif i_unit == "F" and o_unit == "K":
result = int(((degree * 1.8) +32)+ 273.15)
print("{:0.2f}°{} ⇒ {:0.2f}°{}".format(degree,i_unit,result,o_unit))
elif i_unit == "F" and o_unit == "C":
result = int((degree - 32) / 1.8)
print("{:0.2f}°{} ⇒ {:0.2f}°{}".format(degree,i_unit,result,o_unit))
elif i_unit == "K" and o_unit == "C":
result = int(degree - 273.15)
print("{:0.2f}°{} ⇒ {:0.2f}°{}".format(degree,i_unit,result,o_unit))
elif i_unit == "K" and o_unit == "F":
result = int(((degree - 273.15) - 32) / 1.8)
print("{:0.2f}°{} ⇒ {:0.2f}°{}".format(degree,i_unit,result,o_unit))
else:
while True:
input_unit, target_unit = input("Input the temperature and the unit to convert it to?: ").split()
if input_unit[-1].upper() != "C" or target_unit.upper() != "F":
print("You enterd an invalid unit. Please enter again: ")
在這里,我建議您分幾個步驟分解程序,首先詢問溫度,然后使用函數進行轉換,然后顯示結果。
def temperatureConversions(degree, i_unit, o_unit):
if i_unit == "C" and o_unit == "F":
return int((1.8 * degree) + 32)
elif i_unit == "C" and o_unit == "K":
return int(degree + 273.15)
elif i_unit == "F" and o_unit == "K":
return int(((degree * 1.8) +32)+ 273.15)
elif i_unit == "F" and o_unit == "C":
return int((degree - 32) / 1.8)
elif i_unit == "K" and o_unit == "C":
return int(degree - 273.15)
elif i_unit == "K" and o_unit == "F":
return int(((degree - 273.15) - 32) / 1.8)
valueCorrect = False
while(not valueCorrect):
degree = input("Please enter a temperature (ex: 47C):\n")
o_unit = input("Please enter the output unit desired(ex: C, F, K):")
if(degree[:-1].isdigit()):
i_unit, degree = degree[-1], int(degree[:-1])
if(i_unit and o_unit in ['C', 'F', 'K']):
valueCorrect = True
else:
print("Please write correct values of unit !")
else:
print("Please write correct values of temperature !")
resultConversion = temperatureConversions(degree, i_unit, o_unit)
print("{:0.2f}°{} ⇒ {:0.2f}°{}".format(degree,i_unit,resultConversion,o_unit))
向我確認它對你有用。
一種更簡單的方法是將輸入轉換為規范單位(例如,K),然后相應地轉換為所需的輸出單位。
def c_to_k(degrees: float) -> float:
return degrees + 273.15
def k_to_c(degrees: float) -> float:
return degrees - 273.15
def f_to_k(degrees: float) -> float:
return degrees * 1.8 + 32 + 273.15
def k_to_f(degrees: float) -> float:
return (degrees - 273.15 - 32) / 1.8
iconv = {
"c": c_to_k,
"f": f_to_k
}
oconv = {
"c": k_to_c,
"f": k_to_f
}
def temperature_conversion(
temperature: float,
input_unit: str,
output_unit: str):
input_unit = input_unit.lower()
if input_unit != "k":
temperature = iconv[input_unit](temperature)
output_unit = output_unit.lower()
if output_unit != "k":
temperature = oconv[output_unit](temperature)
return temperature
簡而言之, iconv
和oconv
字典將if
語句替換為簡單的字典查找,該字典查找返回要調用的函數對象以執行規范轉換。
根據您的受眾,您可能希望添加錯誤檢查以在傳入無效單元時引發比KeyError
更詳細的異常。
如果這看起來太復雜了,那么更簡單的實現可能會避免字典查找,而只需使用if
語句首先將輸入轉換為規范單位,然后再將其轉換為所需的輸出單位。 在這種情況下,可以通過將規范單位更改為 C 來簡化代碼,但是:
if input_unit == "f":
temperature = (temperature - 32) / 1.8
elif input_unit == "k":
temperature -= 273.15
if output_unit == "k":
temperature += 273.15
elif output_unit == "f":
temperature = temperature * 1.8 + 32
如果您需要高精度的結果,您可能希望避免通過兩次單獨的計算來進行單位之間的轉換,因為浮點錯誤會加重並降低結果的准確性。 在這種情況下,您的原始代碼的復雜性基本上無法避免。(也許另見Is floating point math broken? Converting Fahrenheit to Fahrenheit 有點可能不會准確返回輸入數字!)但是您的代碼強制float
s 為int
s 顯然會不必要地損失更多的精度。
注意函數本身不print
任何東西,它只是返回一個數字。 一種常見的設計是將可重用功能與用戶界面設計分開,因此向用戶顯示結果(或做任何其他你想做的事情)的責任落在調用者身上。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.