一、 一个简单示例

使用if语句来正确处理特殊情形。对于大多数汽车,以首字母大写的方式打印出来,对于宝马汽车,以全大写的方式打印出来

cars = ['audi','bmw','subaru','toyata']
for car in cars:
    if car == 'bmw':
        print(car.upper())
    else:
        print(car.title())
        
运行结果:
Audi
BMW
Subaru
Toyata

二、条件测试

每条if语句的核心都是一个值为True或False的表达式,这种表达式被称为条件测试。
Python根据条件测试的值为True还是False来决定是否执行if语句中的代码,如果条件测试的值为True,Python就执行紧跟在if语句后面的代码,如果为False,Python就忽略这些代码。
1. 检查两个值相等
两个等号(==

car = 'bmw'
print(car == 'bmw')

运行结果
True

一个等号是陈述,两个等号是发问。
2. 检查两个值相等时区分大小写
两个大小写不同的值会被视为不相等

car = 'bmw'
print(car == 'BMW')

运行结果
False

可以使用函数lower(),upper(),title(),将变量的值统一转换格式,再进行比较。

car = 'bmw'
new_car = 'BMW'
print(car.lower() == new_car.lower())

运行结果
True

3. 检查两个值不相等
要判断两个值不相等,使用(!=),其中惊叹号表示不。

car = 'bmw'
new_car = 'BMW'
print(car != new_car)

运行结果:
True

4. 比较数字
条件语句中可以包含各种数学比较,如等于(==),不等于(!=)、小于(<)、小于等于(<=)、大于(>)、大于等于(>=

age = 16
if age < 18:
    print("You are a minor!")
运行结果:
You are a minor!

5. 检查多个条件
需要使用关键字andor,将两个测试条件合而为一。

关键字and,多个条件都为真,才判定为True

age = 16
if age>10 and age<18:
    print("你不是18岁")
else:
    print("hello python")
运行结果:
你不是18岁

关键字or,只要有一个条件为真,就判定为True

age = 16
if age<17 or age>18:
    print("你不是18岁")

运行结果:
你不是18岁

6. 检查特定值包含在列表中
关键字in让Python检查指定元素是否包含在列表中

cars = ['audi','bmw','subaru','toyata']
print('byd'in cars)
print('bmw' in cars)
运行结果:
False
True

7. 检查特定值不包含在列表中
关键字:not in

cars = ['audi','bmw','subaru','toyata']
print('byd'not in cars)
print('bmw' not in cars)
运行结果:
True
False
  1. 布尔表达式子
    布尔表达式是条件测试的别名,与条件表达式一样,布尔表达式的结果只有TrueFalse两个值。

三、if语句

  1. 简单的if语句
if condition_test:
    do something

if语句中,缩进的作用于for循环中相同。如果条件测试通过,则将执行if语句后面所有缩进的代码,否则忽略它们。

2. if-else语句
如果条件测试通过,则执行if语句,没有条件测试没有通过,则执行else语句。

age = 18
if age>= 18:
    print("You are old enough to vote!")
else:
    print("Sorry,you are too young to vote")

运行结果:
You are old enough to vote!

3. if-elif-else结构
Python只执行if-elif-else结构中的一个代码块,一次检查每个条件测试,直到通过了条件测试。测试通过后,Python将执行紧跟在它后面的代码,并跳过余下的测试。

age = 18
if age<4:
    price=0
elif age<18:
    price=5
else:
    price=10
print("Your admission cost is $"+str(price)+".")
运行结果:
Your admission cost is $10.

4. 使用多个elif代码块
可以根据需要使用任意数量的elif代码块

age = 66
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.

5. 省略else代码块
Python并不要求if-elif结构后面必须有else代码块。else是一条包罗万象的语句,只要不满足任何if或elif中的条件测试,其中的代码都会执行,这可能会引入无效甚至恶意的数据。如果知道最终要测试的条件,应考虑使用一个elif代码块来代替else代码块。

age = 66
if age<4:
    price=0
elif age<18:
    price=5
elif age<65:
    price=10
elif 65<=age<100:
    price=5
print("Your admission cost is $"+str(price)+".")
运行结果:
Your admission cost is $5.
  1. 测试多个条件
    if-elif-else结构功能强大,当仅仅适用于只有一个条件满足的情况,遇到了通过的测试后,Python就跳过余下的测试。然而,有多个条件为True,且你需要在每个条件为True时都采取相应的措施时,需要使用多个独立的if语句。
cars = ['audi','bmw','subaru','toyata']
if 'audi' in cars:
    print("audi is my choose.")
if 'subaru' in cars:
    print('subaru is my choose.')
if 'byd' in cars:
    print('byd is my choose.')

print("end")

总之,如果指向执行一个代码块,就用if-elif-else结构,如果想要运行多个代码块,就使用一系列独立的if语句。

四、使用if语句处理列表

1. 检查特殊元素
使用等于号

cars = ['audi','bmw','subaru','toyata']
for car in cars:
    if car == 'bmw':
        print("sorry, bmw has sold out!")
    else:
        print("Here are the guests who need "+car.title()+".")
print("\nWelcom to visit next time.")

运行结果:
Here are the guests who need Audi.
sorry, bmw has sold out!
Here are the guests who need Subaru.
Here are the guests who need Toyata.

Welcom to visit next time.

2. 确定列表不是空的
if 列表名:如果列表不为空,条件测试为True,如果列表为空,条件测试为False

# cars列表不为空
cars = ['audi','bmw','subaru','toyata']
if cars:
    for car in cars:
        print("Here are the guests who need "+car.title()+".")
else:
    print("Are you sure you want a plain car?")
运行结果:
Here are the guests who need Audi.
Here are the guests who need Bmw.
Here are the guests who need Subaru.
Here are the guests who need Toyata.
# cars列表为空
cars = []
if cars:
    for car in cars:
        print("Here are the guests who need "+car.title()+".")
else:
    print("Are you sure you want a plain car?")

运行结果:
Are you sure you want a plain car?

3. 使用多个列表或元组
4s店拥有的车:cars
客户想买的车:car_needs
如果客户想买的车在4s店中可以找到,则交易成功,否则交易失败。4s店拥有的车,是固定的,可以用列表或元组来存储,客户想买的车不固定,可以用列表来存储。

cars = ('audi','bmw','subaru','toyata')
car_needs = ['byd','bmw','toyata']
for car_need in car_needs:
    if car_need in cars:
        print("We have "+car_need+", Successful transaction")
    else:
        print("Not to exist "+car_need+", transaction failed")
print("Thank you for coming")
运行结果:
Not to exist byd, transaction failed
We have bmw, Successful transaction
We have toyata, Successful transaction
Thank you for coming

五、 设置if语句的格式

在条件测试的格式设置方面,PEP8提供的唯一建议是,在诸如==>=<=等比较运算符两边各添加一个空格。
if age < 4: 要比 if age<4:的代码更好。

六、 小结

学习了条件测试,结果只为True/False
if语句,if-elif-else结构, for循环和if语句结合使用,可以对特定的列表元素进行处理,if语句中条件测试的代码格式建议。