python chapter 4 Conditionals条件语句

目录

一、if 语句

二丶if-else 语句

三丶if-elif-else 语句

四丶match...case

总结


一、if 语句

Conditionals Make Decisions

if 语句流程

举个例子

def f(x):

        print("A", end="")

        if x == 0:

                print("B", end=" ")

                print("C", end=" ")

        print("D")

f(1)

AD

一个更有意思的例子:

二丶if-else 语句

def f(x):

        print("A", end="")

        if x == 0:

                print("B", end="")

                print("C", end="")

         else:

                print("D", end="")

        if x == 1:

                print("E", end="")

        else:

                print("F", end="")

        print("G")

f(1)

ADEG

三丶if-elif-else 语句

四丶match...case

Python 3.10 增加了 match...case 的条件判断。

match subject:
    case <pattern_1>:
        <action_1>
    case <pattern_2>:
        <action_2>
    case <pattern_3>:
        <action_3>
    case _:
        <action_wildcard>

case _: 类似于 C 中的 default:,当其他 case 都无法匹配时,匹配这条,保证永远会匹配成功。


总结

  • Conditionals Make Decisions.
  • if-else 结构构成了 Python 分支控制,if 还能嵌套使用。
  • 7
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值