python中的“switch/case”语句

本文分享了一个使用Python字典来模拟Switch/Case结构的例子。通过定义一个字典,将不同的输入映射到对应的字符串输出,实现了简单的数字到字符串的转换功能。这种方式简洁且易于维护。
#!/usr/bin/env python

def numbers_to_string(argument):
    switcher = { 
    0:'Zero',
    1:'one',
    2:'two'
    }   
    return switcher.get(argument,'nothing')

if __name__ == '__main__':
    arg = int(raw_input('Enter a number:'))
    print numbers_to_string(arg)

上面是使用字典实现switch/case功能的实现


转载于:https://my.oschina.net/yanxiaoshuai/blog/523641

Python中,没有内置的switch/case语句。然而,可以使用一些替代方法来实现类似的功能。一种常见的方法是使用字典映射和调度方法。通过将不同的选项作为字典的键,将相应的处理逻辑作为字典的值,可以轻松地模拟switch/case语句的效果。这种方法的代码通常更为简洁,而且在运行时可以添加或删除选项。例如,可以使用以下代码实现类似switch/case的效果: ``` def switch_case(value): switcher = { 0: "zero", 1: "one", 2: "two", } return switcher.get(value, 'wrong value') ``` 在上述代码中,switch_case函数接受一个值作为参数,并在字典switcher中查找相应的处理逻辑。如果找到了匹配的键,则返回对应的值;如果没有找到匹配的键,则返回'wrong value'。可以根据实际需要自定义字典的键和值,以实现不同的功能。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [为什么Python中没有Switch/Case语句?](https://blog.youkuaiyun.com/weixin_39968410/article/details/112961877)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *3* [【Python】用Python实现switch case语句](https://blog.youkuaiyun.com/Datapad/article/details/123205438)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值