python分支语句

可以通过下图来简单了解条件语句的执行过程:

if 语句

Python中if语句的一般形式如下所示:

if condition_1: statement_block_1elif condition_2: statement_block_2else: statement_block_3

如果 "condition_1" 为 True 将执行 "statement_block_1" 块语句

如果 "condition_1" 为False,将判断 "condition_2"

如果"condition_2" 为 True 将执行 "statement_block_2" 块语句

如果 "condition_2" 为False,将执行"statement_block_3"块语句

Python 中用 elif 代替了 else if,所以if语句的关键字为:if – elif – else

例:

num=int(input("输入一个数字:"))if num%2==0: if num%3==0: print ("你输入的数字可以整除 2 和 3") else: print ("你输入的数字可以整除 2,但不能整除 3")else: if num%3==0: print ("你输入的数字可以整除 3,但不能整除 2") else: print ("你输入的数字不能整除 2 和 3")

match...case

Python 3.10 增加了 match...case 的条件判断,不需要再使用一连串的 if-else 来判断了。

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 都无法匹配时,匹配这条,保证永远会匹配成功。

实例

mystatus=400

print(http_error(400))

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"

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值