This article was written before Python 3.10 (released Oct 2021). If you are on
Python 3.10 or newer, use the native match statement instead of a dict of lambdas.
defcalculate(operator: str, x: float, y: float) -> float: match operator: case'add': return x + y case'sub': return x - y case'mul': return x * y case'div': return x / y case _: # default raise ValueError(f"unknown operator: {operator}")
Same output as above. The dict-of-lambdas trick still works, but match is the idiomatic
Python 3.10+ way, and it can also match on data structures and guards, not just strings.