match 后的对象会依次与 case 后的内容进行匹配,如果匹配成功,则执行匹配到的表达式,否则直接跳过,_ 可以匹配一切。
语法格式如下:
match subject:case<pattern_1>:<action_1>case<pattern_2>: <action_2>case<pattern_3>: <action_3>case _:<action_wildcard>
case _: 类似于 C 和 Java 中的 default:,当其他 case 都无法匹配时,匹配这条,保证永远会匹配成功。
实例
def http_error(status):
match status:
case 400: return"Bad request"
case 404: return"Not found"
case 418: return"I'm a teapot"
case _: return"Something's wrong with the internet"