Python中没有switch/case语句,我们可以用elif语句来模拟它.
如:
if user.cmd == 'create':
action = "create item"
elif user.cmd == 'delete':
action = 'delete item'
elif user.cmd == 'update':
action = 'update item'
else:
action = 'invalid choice... try again!'
简化一下可以变为如下形式:
if user.cmd in ('create', 'delete', 'update'):
action = '%s item' % user.cmd
else:
action = 'invalid choice... try again!'
使用字典要比使用elif或者for循环快很多.