question 334 Functional & Dynamic Python · easy
Format values through a registry
A product page shows values of different kinds. Write format_value(value, kind) using a dictionary from kind to a formatting function, not an if/elif chain: "grams" → "13.2 g", "kcal" → "363 kcal" (rounded to a whole number), "percent" → "27.8%" (one decimal), "grade" → "Nutri-Score B". An unknown kind raises ValueError.
Function
format_value(value, kind)gramsthe number as Python prints it, then
gkcalrounded to a whole number, then
kcalpercentone decimal place, then
%grade
Nutri-Score and the letter in capitalsExamples
callformat_value(13.2, 'grams')returns'13.2 g'
callformat_value(363.4, 'kcal')returns'363 kcal'
callformat_value(27.777, 'percent')returns'27.8%'
callformat_value('b', 'grade')returns'Nutri-Score B'