前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python switch-case

python switch-case

作者头像
zero000
发布2021-07-26 20:39:49
4210
发布2021-07-26 20:39:49
举报
文章被收录于专栏:程序员菜谱程序员菜谱
Switch-Statement-Flowchart.png
Switch-Statement-Flowchart.png

python原生没有switch case的语法

使用下面的方案可以替代

代码语言:txt
复制
# Function to convert number into string
# Switcher is dictionary data type here
def numbers_to_strings(argument):
    switcher = {
        0: "zero",
        1: "one",
        2: "two",
    }
  
    # get() method of dictionary data type returns 
    # value of passed argument if it is present 
    # in dictionary otherwise second argument will
    # be assigned as default value of passed argument
    return switcher.get(argument, "nothing")
  
# Driver program
if __name__ == "__main__":
    argument=0
    print (numbers_to_strings(argument))

C++ 的方法

代码语言:txt
复制
#include<bits/stdc++.h>
using namespace std;
  
// Function to convert number into string
string numbers_to_strings(int argument){
    switch(argument) {
        case 0:
            return "zero";
        case 1:
            return "one";
        case 2:
            return "two";
        default:
            return "nothing";
    };
};
  
// Driver program
int main()
{
    int argument = 0;
    cout << numbers_to_strings(argument);
    return 0;
}

参考:

  1. https://www.geeksforgeeks.org/switch-case-in-python-replacement/

本文系转载,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文系转载前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档