条件测试
- 每个if语句的核心都是一个值为True或False的表达式。这种表达式称为条件测试
1.检查是否相等当前值同特定值比较
cars=['audi','bmw','subaru','toyota']
for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.title())
输出:
Audi
BMW
Subaru
Toyota
网站采用类似方式让用户输入的数据符合特定的格式。
在python中检查是否相等时区分大小写,两个大小写不同的值会被视为不相等,网站可能使用类似的方式确保用户名是独一无二的,而并非只是与另一个用户名的大小写不同。
2.检查是否不相等
- 要判断两个值是否不等,可结合使用惊叹号和等号(!=)其中惊叹号表示不
cars=['audi','bmw','subaru','toyota']
for car in cars:
if car != 'bmw':
print(car.upper())
else:
print(car.title())
AUDI
Bmw
SUBARU
TOYOTA
3.检查多个条件
1.使用and检查多个条件
- 使用and将两个条件测试合而为一,如果每个测试都通过,为True,否则为False.
age_0=22
age_1=23
if age_0>=20 and age_1 >= 30:
print(True)
else:
print(False)
2.使用or检查多个条件
- 使用or检查多个条件,只要至少有一个条件满足,就能通过这个测试。
4.检查特定值是否包含在列表中
- 要检查特定值是否包含在列表中,可以使用关键字in
5.检查特定值是否不包含在列表中
- 要检查特定值不包含在列表中,使用关键字not in
6.布尔表达式
- 布尔表达式不过是条件测试的别名。它的值要么是true,要么是false.
if语句
1.if-else语句
- 在条件测试通过时执行一个操作,在没有通过时执行另一个操作。
2.if-elif-else语句
- 检查需要超过两个。
- 仅适合用于只有一个条件满足的情况:python遇到通过了的测试后,就跳过余下的测试。
- 如果想执行一个代码块,就使用if-else-if结构,如果要运行多个代码块,就要使用一系列独立的if语句。
age =12
if age<4:
print('your admission cost is 0')
elif age<18:
print('you admission cost is 5')
else:
print('your admission cost is 10')
简化代码:
age = 12
if age <4:
price=0
elif age <18:
price=5
else:
price=10
print('you admission cost is ' +str(price))
3.使用多个elif代码块
- 如果在前面的代码中加入一个测试条件:年龄65岁以上的打五折
age = 66
if age <4:
price=0
elif age <18:
price= 5
elif age>65:
price=5
else:
price=10
print('you admission cost is ' +str(price))
4.省略else代码块
- 只要不满足if或elif中的条件测试,其中的代码就会执行,这可能会引入无效甚至恶意的数据。
- 如果知道最终要测试的条件,应考虑使用一个elif代码块来代替else结构。
age=66
if age <4:
price=0
elif age <18:
price= 5
elif age<65:
price=10
elif age>=65:
price=5
print('you admission cost is ' +str(price))
使用if语句处理列表
1.检查特殊元素
2.确定列表不是空的
- 如果列表为空,就向顾客确认他是否要点普通披萨;
- 如果列表不空,就显示在披萨中添加的各种配料的输出。
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?")
在if语句中将列表名用在条件表达式中,python将在列表至少包含一个元素时返回True,并在列表为空时返回False
3.使用多个列表
- 第一个列表包含披萨店供应的配料
- 第二个列表包含顾客点的配料
- 对于第二个列表中的元素,都要检查它是否是披萨店供应的配料,再决定是否在披萨中添加它。
available_toppings=['mushrooms','olives','green peppers','pepperoni']
requested_toppings=['mushrooms','olives']
for requested_topping in requested_toppings:
if requested_topping in available_toppings:
print("Adding" + requested_topping )
else:
print("Sorry,we do not have "+requested_topping)
print("\nFinished making your pizza")