Python编程 从入门到实践 第五章 if语句

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. 条件测试

  1. 每条if 语句的核心都是一个值为True或False的表达式,这种表达式称为条件测试
  2. 如果条件测试值为True,Python就执行紧跟在if后面的代码
  3. 如果条件测试值为False,Python就忽略这些代码

2.1 检查是否相等

  1. 一个等号 = 将等号右侧的值赋给等号左侧,是陈述
  2. 两个等号 == 是相等运算符,是质询
  3. != 是不等运算符
  4. 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 检查特定值是否包含在列表中

  1. 特定值包含在列表中,用关键字 in
  2. 特定值不包含在列表中,用关键字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 布尔表达式

  1. 布尔表达式是条件测试的别名
  2. 与条件表达式一样,布尔表达式的结果要么为True,要么为False

3. if 语句

3.1 简单的if语句

  1. 最简单的if语句只有一个测试和一个操作;
  2. if 语句若将列表名用在条件表达式中时,Python将在列表至少包含一个元素时返回True
  3. 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 语句

  1. 需要检查超过两个条件的情形
>>> 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.
  1. 简洁代码

  2. 效率更高,修订后的代码更容易修改

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-… 语句

  1. Python并不要求 if-elif 结构后面必须有else代码块
  2. else是一条包罗万象的语句,只要不满足 if 或 elif 中的条件测试,其中的代码就会执行,这可能会引入无效甚至恶意数据
  3. 如果你知道最终要测试的条件,应考虑使用 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 测试多个条件

  1. 可能有多个条件为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
  1. 对比操作
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对代码的解读,只是让代码可读性更强

6. 章节跳转

  1. Python编程 从入门到实践 第一章 起步
  2. Python编程 从入门到实践 第二章 变量和简单数据类型
  3. Python编程 从入门到实践 第三章 列表简介
  4. Python编程 从入门到实践 第四章 列表操作
  5. Python编程 从入门到实践 第五章 if语句
  6. Python编程 从入门到实践 第六章 字典
  7. Python编程 从入门到实践 第七章 用户输入和while循环
  8. Python编程 从入门到实践 第八章 函数
  9. Python编程 从入门到实践 第九章 类
  10. Python编程 从入门到实践 第十章 文件和异常
  11. Python编程 从入门到实践 第十一章 测试代码
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值