Dispatch tables in Python: Replace if/elif with a dict of functions

Dispatch tables in Python: Replace if/elif with a dict of functions

Instead of choosing which Python function to run with if/elif/else, use a dispatch table — a dict with functions as values:

from operator import add, sub, mul
ops = {'+':add, '-':sub, '*':mul}
s = input('Enter +, -, or * : ')
r = ops[s](10, 20)
print(f'10 {s} 20 = {r}')