文章目录
1. 简单示例
>>> cars = ['audi','bmw','subaru','toyota']
>>> for car in cars:
... if car == 'bmw':
... print(car.upper())
... else:
... print(car.title())
...
Audi
BMW
Subaru
Toyota
2. 条件测试
- 每条if 语句的核心都是一个值为True或False的表达式,这种表达式称为条件测试
- 如果条件测试值为True,Python就执行紧跟在if后面的代码
- 如果条件测试值为False,Python就忽略这些代码
2.1 检查是否相等
- 一个等号 = 将等号右侧的值赋给等号左侧,是陈述
- 两个等号 == 是相等运算符,是质询
- != 是不等运算符
- Python中检查是否相等时是区分大小写的
>>> car = 'Audi'
>>> car == 'Audi'
True
>>>
>>> car = 'Audi'
>>> car == 'audi'
False
>>>
>>> car = 'Audi'
>>> car != 'audi'
True
>>>
>>> car = 'Audi'
>>> car.lower() == 'audi' #函数lower()不会修改存储在car中的值
True
>>> car
'Audi'
2.2 比较数字
>>> age = 19
>>> age == 19
True
>>> age < 21
True
>>> age <= 21
True
>>> age > 21
False
>>> age >= 21
False
2.3 检查多个条件
2.3.1 and
and两侧条件测试必须均为True,结果为True
>>> age_1 = 27
>>> age_2 = 17
>>> age_1 >= 18 and age_2 >= 18
False
>>> age_2 =21
>>> age_1 >= 18 and age_2 >= 18
True
2.3.2 or
or两侧条件测试至少有一个为True,结果为True
>>> age_1 = 27
>>> age_2 = 17
>>> age_1 >= 18 or age_2 >= 18
True
>>> age_1 =15
>>> age_1 >= 18 or age_2 >= 18
False
2.4 检查特定值是否包含在列表中
- 特定值包含在列表中,用关键字 in
- 特定值不包含在列表中,用关键字not in
>>> requested_toppings = ['mushrooms','onions','pineapple']
>>> 'mushrooms' in requested_toppings
True
>>> 'pepperoni' in requested_toppings
False
>>> 'pepperoni' not in requested_toppings
True
2.5 布尔表达式
- 布尔表达式是条件测试的别名
- 与条件表达式一样,布尔表达式的结果要么为True,要么为False
3. if 语句
3.1 简单的if语句
- 最简单的if语句只有一个测试和一个操作;
- if 语句若将列表名用在条件表达式中时,Python将在列表至少包含一个元素时返回True
- if 语句中,缩进的作用与for循环中相同。如果测试通过,将执行if语句后面所有缩进的代码行,否则将忽略它们
>>> i_meet_you_before = [1]
>>> if i_meet_you_before:
... '单身狗'
...
'单身狗'
>>> age = 19
>>> if age >= 18:
... print("You are old enough to votel!")
... print("Have you registered to vote yet?")
...
You are old enough to votel!
Have you registered to vote yet?
3.2 if-else 语句
在这种 if-else 语句结构中,总是会执行两个操作中的一个
>>> age = 17
>>> if age >= 18:
... print("You are old enough to votel!")
... print("Have you registered to vote yet?")
... else:
... print("Sorry,you are too young to vote.")
... print("Please register to vote as soon as you turn 18!")
...
Sorry,you are too young to vote.
Please register to vote as soon as you turn 18!
3.3 if-elif-else 语句
- 需要检查超过两个条件的情形
>>> age = 12
>>> if age < 4:
... print("Your admission cost is $0.")
... elif age < 18:
... print("Your admission cost is $5.")
... else:
... print("Your admission cost is $10.")
...
Your admission cost is $5.
-
简洁代码
-
效率更高,修订后的代码更容易修改
age = 12
if age < 4:
price = 0
elif age < 18:
price = 5
else:
price = 10
print("Your admission cost is $"+str(price)+".")
Your admission cost is $5.
3.4 if-elif-elif-… -else 语句
根据需要使用任意数量的elif
age = 12
if age < 4:
price = 0
elif age < 18:
price = 5
elif age < 65:
price = 10
else:
price = 5
print("Your admission cost is $"+str(price)+".")
Your admission cost is $5.
3.5 if-elif-elif-… 语句
- Python并不要求 if-elif 结构后面必须有else代码块
- else是一条包罗万象的语句,只要不满足 if 或 elif 中的条件测试,其中的代码就会执行,这可能会引入无效甚至恶意数据
- 如果你知道最终要测试的条件,应考虑使用 elif 代码块来代替 else 代码块
age = 12
if age < 4:
price = 0
elif age < 18:
price = 5
elif age < 65:
price = 10
elif age >= 65:
price = 5
print("Your admission cost is $"+str(price)+".")
Your admission cost is $5.
3.6 测试多个条件
- 可能有多个条件为True,且需要在每个条件为True时都采取相应的措施时,适合用下面这种方法
requested_toppings = ['mushrooms','extra cheese']
if 'mushrooms' in requested_toppings:
print("Adding mushrooms.")
if 'pepperoni' in requested_toppings:
print("Adding pepperoni.")
if 'extra cheese' in requested_toppings:
print("Adding extra cheese.")
print("\nFinished making your pizzal")
Adding mushrooms.
Adding extra cheese.
Finished making your pizzal
- 对比操作
requested_toppings = ['mushrooms','extra cheese']
if 'mushrooms' in requested_toppings:
print("Adding mushrooms.")
elif 'pepperoni' in requested_toppings:
print("Adding pepperoni.")
elif 'extra cheese' in requested_toppings:
print("Adding extra cheese.")
print("\nFinished making your pizza!")
Adding mushrooms.
Finished making your pizza!
4. 使用if 语句处理列表
当列表为空时,此时访问元素将报错
>>> bicycles = []
>>> print(bicycles[0])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
4.1 检查特殊元素
requested_toppings = ['mushrooms','green peppers','extra cheese']
for requested_topping in requested_toppings:
if requested_topping == 'green peppers':
print("Sorry,we are out of green peppers right now.")
else:
print("Adding " + requested_topping + ".")
print("\nFinished making your pizza!")
Adding mushrooms.
Sorry,we are out of green peppers right now.
Adding extra cheese.
Finished making your pizza!
4.2 确定列表不是空的
在if 语句中将列表名用在条件表达式中时,Python将在列表至少包含一个元素时返回True,并在列表为空时返回False
requested_toppings = []
if requested_toppings:
for requested_topping in requested_toppings:
print("Adding " + requested_topping + ".")
print("\nFinished making your pizza!")
else:
print("Are you sure you want a plain pizza?")
Are you sure you want a plain pizza?
4.3 使用多个列表
available_toppings = ['mushrooms','olivers','green peppers',
'pepperoni','pineapple','extra cheese']
requested_toppings = ['mushrooms','french fries','extra cheese']
for requested_topping in requested_toppings:
if requested_topping in available_toppings:
print("Adding " + requested_topping + ".")
else:
print("Sorry,we don't have " + requested_topping + ".")
print("\nFinished making your pizza!")
Adding mushrooms.
Sorry,we don't have french fries.
Adding extra cheese.
Finished making your pizza!
5. 设置if 语句的格式
在条件测试的格式设置方面,PE8建议在诸如==、>=、<=等比较运算符的两边各添加一个空格
空格不会影响Python对代码的解读,只是让代码可读性更强