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循环快很多.
本文介绍了如何在Python中利用elif语句实现switch/case的功能,通过实例展示了一种简化版的写法,并指出使用字典进行操作能够显著提高效率。
3530

被折叠的 条评论
为什么被折叠?



