[英]How to store formula,in function, as string to output later?
我正在嘗試創建一個函數,在其中存儲轉換器的公式。 當需要X公式時,將從中調用它。 當使用簡單的0:a + b嘗試時,返回時可以使用,但是嘗試將其存儲為字符串meters_to_foots時 ,則不起作用。 我需要將該公式存儲為某些東西,因為以后需要輸出它。這是我遇到問題的代碼的一部分。 NameError:未定義名稱“ meters_input”
def my_formulas(i):
switcher={
0:(meters_input/0.3048)
}
return switcher.get(i,"Invalid formula")
distance_pick=input("Please pick one of the current convertions : \n \n1.Meters to X \n2.Inches to X \n3.Feets to X ")
if(distance_pick=="1"):
cls()
distance_choice = input ("Please select which converter would you like to use ! : \n \n1.Meter to Foot \n2.Meter to Yard \n3.Meters to Inches ")
if(distance_choice=="1"):
meters_input=float(input("Make sure to enter distance in Meters ! : "))
my_formulas(0)
print ("\nYou entered", meters_input , "meters, which is equal to",my_formulas(0),"foots.")
time.sleep (3)
cls ()
read_carefully_message()
如果這些將始終是簡單函數,則可以為此使用lambda
表達式:
def my_formulas(i):
switcher= {
0:lambda meters_input: meters_input/0.3048
}
return switcher.get(i,"Invalid formula")
my_formulas(0)(27) #88.58267716535433
如果函數查找始終是從零開始的數字,則最好將函數存儲為數組。 您也可以執行以下操作:
def my_formulas(index):
def meters2Feet(meters):
return meters/0.3048
def hours2Minutes(hours):
return hours * 60
def invalid(*args):
return "Invalid formula"
lookup = [
meters2Feet,
meters2Feet
]
if index >= len(lookup):
return invalid
return lookup[index]
my_formulas(0)(27) # 88.58267716535433
它有點復雜,但可能更容易閱讀和理解。
要在Python中創建函數,請使用lambda函數或常規函數定義。 示例分別是:
def divide(meters_input):
return meters_input / 0.3048
要么
divide = lambda meters_input: meters_input / 0.3048
通常,常規函數定義是首選,因為它可以提高可讀性。 您可以如下定義函數映射:
def my_formulas(i):
switcher={
0:divide # do not write divide()
}
嘗試將功能更改為此:
def my_formulas(i):
switcher = (i/0.3048)
return switcher
函數中的“ i”是函數的局部變量。 在您的代碼中,您正在將0傳遞給my_formulas()函數。 然后,我變為0,但是meters_input超出了該函數的范圍。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.