我對Python和編程完全陌生,但我正在嘗試使用更實用的方法來學習它。如何創建包含函數名稱的列表?
我想要做的是練習轉換不同的單位,例如,磅 - >公斤,腳 - >米等
我已經定義的所有功能,針對不同單位對:
def kg_to_g(value):
return round(value*1000.0,2)
def g_to_kg(value):
return round(value/1000.0,2)
def inch_to_cm(value):
return round(value*2.54,2)
def cm_to_inch(value):
return round(value/2.54,2)
def ft_to_cm(value):
return round(value*30.48,2)
等
,並創建了一個清單,這些函數名稱:
unit_list = ['kg_to_g','g_to_kg','inch_to_cm','cm_to_inch',
'ft_to_cm','cm_to_ft','yard_to_m','m_to_yard',
'mile_to_km','km_to_mile','oz_to_g','g_to_oz',
'pound_to_kg','kg_to_pound','stone_to_kg','kg_to_stone',
'pint_to_l','l_to_pint','quart_to_l','l_to_quart',
'gal_to_l','l_to_gal','bar_to_l','l_to_bar']
程序應該隨機選擇一個單元對(例如公斤─>磅)和值(例如134.23),並且用戶將被要求的那些值進行轉換。
random_unit = random.choice(unit_list)
lower = 0.1001
upper = 2000.1001
range_width = upper - lower
ranval = round(random.random() * range_width + lower, 2)
當用戶輸入答案,程序應該比較答案與函數定義的計算,並告訴用戶,如果它是一個正確的答案或錯誤的答案:
def input_handler(answer):
if answer == random_unit(ranval):
label2.set_text("Correct!")
else:
label2.set_text("Wrong!")
不幸的是,這樣的程序沒有按」將不起作用,並且codesculptor(codesculptor.org)與返回錯誤
TypeError: 'str' object is not callable
可能有人請向我解釋什麼是錯的代碼,並提出一些解決日問題。
在'random_unit = random.choice(unit_list)'後面加上'random_unit = globals()[random_unit]'。 –
'random_unit = random.choice(unit_list)':這一行將隨機指定一個'unit_list'(這是一個'str'列表)到'random_unit'。然後你調用'random_unit(ranval)',所以你使用'str'就像一個函數(可調用函數是函數的另一個名稱)。 – kjaquier