一、条件测试

1. 检查是否相等

每条 if 语句的核心都是一个值为 True 或 False 的表达式,这种表达式称为条件测试。

使用两个等号(==)检查是否相等,这个相等运算符在它两边的值相等时返回 True,否则返回 False。

>>> car = 'bmw'                                                                  
>>> car == 'bmw'                                                                 
True

两个大小写不同的值被视为不相等:

>>> car = 'Audi'                                                                 
>>> car == 'audi'                                                                
False

lower() 方法不会修改存储在变量 car 中的值,因此进行这样的比较不会影响原来的变量:

>>> car = 'Audi' 
>>> car.lower() == 'audi'                                                       
True

2. 检查是否不等

要判断两个值是否不等,可使用不等运算符(!=)。

requested_topping = 'mushrooms'
if requested_topping != 'anchovies':
    print("hello, python!".title())
'''
结果:
Hello, Python!
'''

3. 数值比较

比较相等:

>>> age = 18                                                                     
>>> age == 18                                                                    
True

比较不相等: 

answer = 17
if answer != 12:
    print('hi, python')
'''
结果:
hi, python
'''

小于(<)、小于等于(<=)、大于(>)、大于等于(>=)

>>> age = 19                                                                     
>>> age < 20                                                                     
True                                                                             
>>> age <= 20                                                                    
True                                                                             
>>> age > 13                                                                     
True                                                                             
>>> age >= 13                                                                    
True

4. 检查多个条件

使用 and 检查多个条件:果每个条件测试都通过了,整个表达式就为 True;如果至少一个条件测试没有通过,整个表达式就为 False。

>>> age_0 = 22                                                                                                          
>>> age_1 = 18                                                                                                          
>>> age_0 >= 24 and age_1 >=21                                                                                          
False                                                                                                                   
>>> age_0 >= 23 and age_1 <=20                                                                                          
False                                                                                                                   
>>> age_0 >= 20 and age_1 <=21                                                                                          
True 

使用 or 检查多个条件:键字 or 也能够让你检查多个条件,但只要满足其中一个条件,就能通过整个条件测试。仅当所有条件测试都没有通过时,使用 or 的表达式才为 False。

>>> age_0 = 22                                                                                                          
>>> age_1 = 18                                                                                                          
>>> age_0 >= 24 or age_1 >=21                                                                                          
False                                                                                                                   
>>> age_0 >= 23 or age_1 <=20                                                                                          
Ture                                                                                                                   

5. 检查特定的值是否在列表中

检查特定的值是否在列表中:要判断特定的值是否在列表中,可使用关键字 in。

>>> arr = ['anna','lisa','laury']                                                                                       
>>> 'anna' in arr                                                                                                       
True                                                                                                                    
>>> 'xiaoli' in arr                                                                                                     
False

6. 检查特定的值是否不在列表中

检查特定的值是否不在列表中:确定特定的值不在列表中可使用关键字 not in。

banned_users = ['andrew', 'carolina', 'david']
user = 'marie'
if user not in banned_users:
    print('user not in banned_users')

二、if语句

1. 简单的if语句

age = 18
if age >= 18:
    print('You are old enough to vote.')
'''
结果:You are old enough to vote.
'''

2. if-else语句

if-else 语句块类似于简单的 if 语句,但其中的 else 语句让你能够指定条件测试未通过时要执行的操作。

age = 17
if age >= 18:
    print('You are old enough to vote.')
else:
    print('Sorry, you are not old enough to vote.')
'''
结果:Sorry, you are not old enough to vote.
'''

3. if-elif-else语句

你经常需要检查两个以上的情形,此时可使用 Python 提供的 if-elif-else 语句。Python 只执行 if-elif-else 结构中的一个代码块。

age = 18
if age < 4:
    print('"Your admission cost is $0.')
elif 4 <= age < 18:
    print('Y"Your admission cost is $25.')
else:
    print('Your admission cost is $40.')
'''
结果: Your admission cost is $40
'''

4. 使用多个elif

age = 67
if age < 4:
    print("Your admission cost is $0.")
elif age < 18:
    print("Your admission cost is $25.")
elif age < 65:
    print("Your admission cost is $40.")
else:
    print("Your admission cost is $20.")

'''
结果:Your admission cost is $20.
'''

5. 省略else

age = 67
if age < 4:
    print("Your admission cost is $0.")
elif age < 18:
    print("Your admission cost is $25.")
elif age < 65:
    print("Your admission cost is $40.")
elif age >= 65:
    print("Your admission cost is $20.")

'''
结果:Your admission cost is $20.
'''

6. 多个条件

requested_toppings = ['mushrooms', 'extra cheese']
if 'mushrooms' in requested_toppings:
    print('Adding mushrooms')
if 'pepperoni' in requested_toppings:
    print('Adding pepperoni')
print('\nFinished making your pizza!')

'''
结果:
Adding mushrooms

Finished making your pizza!
'''

三、if 语句处理列表

1.检查特殊元素

if 语句检查顾客点的是否是青椒。如果是,就显示一条消息,指出不能点青椒的原因。else 代码块确保其他配料都将被添加到比萨中。

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(f"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!
'''

2. 确定列表非空

下面在制作比萨前检查顾客点的配料列表是否为空。如果列表为空,就向顾客确认是否要点原味比萨(plain pizza);如果列表非空,就像前面的示例那样制作比萨:

requested_toppings = []
if requested_toppings:
    for requested_topping in requested_toppings:
        print(f"Adding {requested_topping}")
    print("\nFinished making your pizza!")
else:
    print("Are you sure you want to plain pizza?")
'''
结果:
Are you sure you want to plain pizza?
'''

3. 使用多个列表

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(f"Adding {requested_topping}")
    else:
        print(f"Sorry, {requested_topping} is not available")
print("\nFinished making your pizza!")

'''
结果
Adding mushrooms
Sorry, french fries is not available
Adding extra cheese

Finished making your pizza!
'''

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐