In general scenario, if you want to check multiple conditions of a simple operation like:
def getFoodPrice(itemName: str) -> float:
if itemName == "Idli":
return 10
if itemName == "Rice":
return 100
else:
raise Exception("Item not found")
In these kinds of scenario we can use Dict object to perform fast and it is very scalable
itemPrice: Dict[str, float] = {
"idli": 10,
"rice": 100
}
def getFoodPrice(itemName: str) -> float:
try:
return itemPrice[itemName.lower()]
except KeyError:
raise Exception("Item not found")
This will reduce the lines of code and improve the scalability. If any new items needs to be added, we can update the dict object not the code.
Top comments (0)