task 5-Conditionals

发布时间 2023-11-29 16:16:46作者: 别小乔我

条件控制

if语句

  • Python 中用 elif 代替了 else if,所以if语句的关键字为:if – elif – else
  • 每个条件后面要使用冒号 :,表示接下来是满足条件后要执行的语句块。
  • 使用缩进来划分语句块,相同缩进数的语句在一起组成一个语句块。
  • 嵌套 if 语句中,可以把 if..elif..else 结构放在另一个 if..elif..else 结构中
if 表达式1:
    语句
    if 表达式2:
        语句
    elif 表达式3:
        语句
    else:
        语句
elif 表达式4:
    语句
else:
    语句
多返回语句
def abs(n):
    if n < 0:
        return -n
    return n

ase语句

match 后的对象会依次与 case 后的内容进行匹配,如果匹配成功,则执行匹配到的表达式,否则直接跳过,_ 可以匹配一切。

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"
mystatus=400
print(http_error(400))

一个 case 也可以设置多个匹配条件,条件使用 | 隔开

...
    case 401|403|404:
        return "Not allowed"