How to use switch in Python?

To implement a switch structure in Python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#!/usr/bin/env python
# -*- coding: utf-8 -*-

switch = {
'add': lambda x, y: x + y,
'sub': lambda x, y: x - y,
'mul': lambda x, y: x * y,
'div': lambda x, y: x / y,
}

if __name__ == '__main__':
print(switch['add'](1, 8))
print(switch['sub'](1, 8))
print(switch['mul'](1, 8))
print(switch['div'](1, 8))

1
2
3
4
9
-7
8
0.125