Python编程:从入门到实践(学习笔记-Charpter 5)

Python编程:从入门到实践(学习笔记-Charpter 5)

十月 17, 2019

Chapter 5 : if 语句

5.1初识 if语句

1
2
3
4
5
6
7
8
9
10
11
12
13
14
cars = ['audi', 'bmw', 'subaru', 'toyota']

for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.title())

---------
Audi
BMW
Subaru
Toyota
---------

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

5.2条件检测

  • 检测是否相等(一个等号是陈述(赋值),两个等号是发问(判断)
1
2
3
4
5
car ='bmw'
car == 'bmw'

#使用两个等号( == )检查 car 的值是否为 'bmw'
#这个相等运算符 在它两边的值相等时返回 True ,否则返回 False 。
  • 检测是否相等时不考虑大小写(转换大小写在比较)
1
2
3
4
5
6
7
8
9
10
11
12
13
car = 'Adui'
car == 'adui'
---
False
---

car = 'Adui'
car.lower() == 'adui'
---
True
---

#如果大小写很重要,这种行为有其优点。但如果大小写无关紧要,而只想检查变量的值,可将变量的值转换为小写,再进行比较:
  • 检测是否不相等(!=)
1
2
3
4
5
requested_topping = 'mushrooms'
if requested_topping != 'anchovies':
print("Hold the anchovies!")

#要判断两个值是否不等,可结合使用惊叹号和等号( != ),其中的惊叹号表示不 ,在很多编程语言中都如此。
  • 比较数字(大于、小于、大于等于、小于等于、等于)
1
2
3
4
5
6
7
8
9
10
11
>>> age = 18
>>> age == 18
True

>>>age = 19
>>>age < 21
Ture
>>>age <= 21
False
>>>age >= 21
False
  • 检测多个条件:

    • 使用and检测多个条件(必须两个同时成立)
    1
    2
    3
    4
    5
    6
    7
    >>> age_0 = 22
    >>> age_1 = 18
    >>> age_0 >= 21 and age_1 >= 21 # (age_0 >= 21) and (age_1 >= 21)增强可读性
    False
    >>> age_1 = 22
    >>> age_0 >= 21 and age_1 >= 21
    True
    • 使用or检测多个条件 (一个成立即为True)
    1
    2
    3
    4
    5
    6
    7
    >>> age_0 = 22
    >>> age_1 = 18
    >>> age_0 >= 21 or age_1 >= 21
    True
    >>> age_0 = 18
    >>> age_0 >= 21 or age_1 >= 21
    False
  • in检测特定值是否包含在列表中

1
2
3
4
5
>>>requested_toppings = ['mushrooms', 'onions', 'pineapple']
>>>'mushrooms' in requested_toppings
True
>>>'pepperoni' in requested_tooppings
False
  • not in检查特定值是否不包含在列表中
1
2
3
4
5
6
7
8
9
10
banned_users = ['andrew', 'carolina', 'david']
user = 'marie'

if user not in banned_users:
print(user.title() + ", you can post a response if you wish.")

---
Marie, you can post a response if you wish.
---
#如果user的值未包含在列表banned_users中,Python将返回True,进而执行缩进的代码行
  • 布尔表达式

布尔表达式于条件表达式一样,布尔表达式的结果要么为True,要么为False

1
2
game_active = True
can_edit = False

:在跟踪程序状态或程序中重要条件方面,布尔值提供了一种高效的方式。

5.3 if 语句

在第 1 行中,可包含任何条件测试,而在紧跟在测试后面的缩进代码块中,可执行任何操作。如果条件测试的结果为 True , Python 就会执行紧跟在 if 语句后面的代码;否则Python 将忽略这些代码。

  • 简单的if 语句
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
age = 19
if age >= 18:
print("You are old enough to vote!")

----
You are old enough to vote!
----

age = 19
if age >= 18:
print("You are old enough to vote!")
print("Have you registered to vote yet?")
----
You are old enough to vote!
Have you registered to vote yet?
----
  • if-else语句
1
2
3
4
5
6
7
8
9
10
age = 17
if age >= 18:
print("You are old enough to vote!")
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
  • if-elif-else 结构
    • 4 岁以下免费;
    • 4~18 岁收费 5 美元;
    • 18 岁(含)以上收费 10 美元。
1
2
3
4
5
6
7
8
9
10
age = input("please input your age: ")

if age < 4 :
print("Your admission cost is $0.") # price = 0
elif age < 18:
print("Your admission cost is $5.") # price = 5
else:
print("Your admission cost is $10.") # price = 10

#print("Your admission cost is $" + str(price) + ".")
  • 使用多个elif代码块
1
2
3
4
5
6
7
8
9
10
11
12
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) + ".")
  • 省略else代码块
1
2
3
4
5
6
7
8
9
10
11
12
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) + ".")
  • 测试多个条件
1
2
3
4
5
6
7
8
9
10
requested_toppings = ['mushroom', 'extra cheese']

if 'mushroom' in requested_tooppings:
print("Adding mushroom.")
if 'pepperoni' in requested_toppings:
print("Adding prpperoni.")
if 'extra cheese' in requested_toppings:
print("Adding extra cheese.")

print ("\n Finished making your pizza!")

5.4使用if语句处理列表

  • 检查特殊元素
1
2
3
4
5
6
7
8
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!")
  • 确定列表不是空的
1
2
3
4
5
6
7
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?")
  • 使用多个列表
1
2
3
4
5
6
7
8
9
available_toppings = ['mushrooms', 'olives', '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!")