可以通过下图来简单了解条件语句的执行过程:
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"