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去吧!!!")
我们先来看一个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的作用: