Appearance
条件判断if 和 模式匹配 match
if语句让你能够检查程序的当前状态,并据此采取相应的措施。
python
cars = ['audi', 'bmw', 'subaru', 'toyota']
for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.title())输出
Audi
BMW
Subaru
Toyota1. 条件测试
每条if语句的核心都是一个值为True或False的表达式,这种表达式被称为条件测试。
Python根据条件测试的值为True还是False来决定是否执行if语句中的代码。如果条件测试的值为True,Python就执行紧跟在if语句后面的代码;如果为False,Python就忽略这些代码。
1.1 == 检查是否相等
- 字符串 区分大小写, 例如 'Audi' 和 'audi' 被认为是不同的字符串。
- 数字 不区分整数和浮点数, 例如 1 和 1.0 被认为是相等的。
- [] 空列表被认为是
False - None 被认为是
False
1.2 != 检查是否不相等
1.3 and 检查多个条件是否都为True
python
1 == 1.0 and 1 == 2 # False
1 == 1.0 and 1 != 2 # True1.4 or 检查多个条件是否有一个为True
python
1 == 1.0 or 1 == 2 # True
1 == 1.0 or 1 != 2 # True1.5 in 检查特定值是否包含在列表中
python
1 in [1, 2, 3] # True
1 in [1.0, 2.0, 3.0] # True
1 in [1.0, 2.0, 3.0] # True1.6 not in 检查特定值是否不包含在列表中
python
1 not in [2, 3] # True
1 not in [1.0, 2.0, 3.0] # False
1 not in [1.0, 2.0, 3.0] # False2. if语句
2.1 简单的if语句
python
if 1 == 1.0:
print('1 is equal to 1.0') # 1 is equal to 1.02.2 if-else语句
python
if 1 == 1.0:
print('1 is equal to 1.0') # 1 is equal to 1.0
else:
print('1 is not equal to 1.0') # 1 is not equal to 1.02.3 if-elif-else结构
python
if 1 == 1.0:
print('1 is equal to 1.0') # 1 is equal to 1.0
elif 1 == 2:
print('1 is equal to 2') # 1 is equal to 2
else:
print('1 is not equal to 1.0 or 2') # 1 is not equal to 1.0 or 22.4 多个elif代码块
python
age = 14
if age < 4:
print('Your ticket is free.')
elif age < 10:
print('Your ticket is $2.50.')
elif age < 18:
print('Your ticket is $5.')
else:
print('Your ticket is $10.')2.5 省略else代码块
Python并不要求if-elif结构后面必须有else代码块
3. 模式匹配 match
例如,某个学生的成绩只能是A、B、C,用if语句编写如下:
python
grade = 'A'
if grade == 'A':
print('score is A.')
elif grade == 'B':
print('score is B.')
elif grade == 'C':
print('score is C.')
else:
print('Invalid score.')如果用match语句改写,则改写如下:
python
grade = 'A'
match grade:
case 'A':
print('score is A.')
case 'B':
print('score is B.')
case 'C':
print('score is C.')
case _: # _表示匹配到其他任何情况
print('Invalid score.')使用match语句时,我们依次用case xxx匹配,并且可以在最后(且仅能在最后)加一个case _表示“任意值”,代码较if ... elif ... else ...更易读。
4. match 匹配列表
match 语句还可以匹配列表,功能非常强大。
match
[ mætʃ ]
n.匹配;匹配项;
python
args = ['gcc', 'hello.c', 'world.c']
match args:
# 表示列表仅有'gcc'一个字符串,报错:
case ['gcc']:
print('gcc: missing source file(s).')
# 表示列表第一个字符串是'gcc',第二个字符串绑定到变量file1,后面的任意个字符串绑定到*files(符号*的作用将在函数的参数中讲解)
case ['gcc', file1, *files]:
print('gcc compile: ' + file1 + ', ' + ', '.join(files))
# 表示列表仅有'clean'一个字符串;
case ['clean']:
print('clean')
# 表示其他所有情况。
case _:
print('invalid command.')