关于python 中match case语句的问题!


    s = input("请输入:")
    match s:
        case 1 | 2:
            print("蒸熊掌")
        case 3 | 4 | 5:
            print("满汉全席")
        case 6 | 7:
            print("水煮肉")
        case _:
            print("吃p去吧!!!")

请问我输入2的时候,为什么程序直接结束,而不是输出对应语句print

input函数接收到的数据都会包装成字符串,也就是说你输入的是2,但是s = '2',字符串的'2'和2肯定是不等的。转换下数据类型s = int(s)

有帮助的话,请点采纳该答案~

 
    s = int(input("请输入:"))
    match s:
        case (1, 2):
            print("蒸熊掌")
        case (3, 4, 5):
            print("满汉全席")
        case (6, 7):
            print("水煮肉")
        case default:
            print("吃p去吧!!!")

  • 可以看下python参考手册中的 python- match 语句
  • 除此之外, 这篇博客: python 3.10更新的一些新特性中的 match-case 部分也许能够解决你的问题, 你可以仔细阅读以下内容或跳转源博客中阅读:
  • 我们先来看一个Java代码示例(无作用,仅语法):
    在这里插入图片描述
    如果是对c或者java等语言有了解的话,应该不难理解,但是,python以前是没有这种语法的,但是在3.10版本之后,python更新了属于自家的match-case语句。
    来看官方文档怎么说:
    A match statement takes an expression and compares its value to successive patterns given as one or more case blocks. This is superficially similar to a switch statement in C, Java or JavaScript (and many other languages), but it can also extract components (sequence elements or object attributes) from the value into variables.
    match 语句采用表达式,并将其值与作为一个或多个事例块给出的连续模式进行比较。这在表面上类似于C,Java或JavaScript(以及许多其他语言)中的switch语句,但它也可以从值中提取组件(序列元素或对象属性)到变量中。
    match-case语法结构如下:
    在这里插入图片描述
    接下来我们一起来看match-case的作用: