5. if语句
if语句
条件测试
检查是否相等
car = 'Bmw'
print(car == 'Bmw')
print(car == 'bmw') #区分大小写
#返回
True
False
car = 'Bmw'
print(car.lower() == 'bmw') #不区分大小写
#返回
True
检查是否不相等
car = 'Bmw'
print(car != 'bmw')
#返回
True
比较数字:== , <, <= , >, >=
检查多个条件
#使用and检查多个条件
(age_0 >= 21) and (age_1 >= 21)
#使用or检查多个条件
(age_0 >= 21) or (age_1 >= 21)
检查特定值是否包含在列表中:关键字 in
检查特定值是否不包含在列表中:关键字 not in
bicyles = ['trek', 'cannondale', 'redline', 'specialized', 'lu']
print('lu' in bicyles)
print('lu' not in bicyles)
布尔表达式
True/False
if语句
简单的if语句
age = 19
if age >= 18:
print("You are old enough to vote!")
if-else 语句
age = 19
if age >= 18:
print("You are old enough to vote!")
else:
print("Sorry, you are too young to vote!")
if-elif-else 语句: 只要有一个测试通过,就会跳过余下的测试
age = 12
if age < 4:
print("You are too ypung!")
elif age < 15:
print("You are young!")
else age >20:
print("You are no young")
使用多个elif代码块:
if-elif-elif-else
省略else代码块:
if-elif-elif-elif
测试多个条件:不管前一个测试是否通过,都将进行这个测试
bicyles = ['trek', 'cannondale', 'redline', 'specialized', 'lu']
if 'trek' in bicyles:
print("1")
if 'cannondale' in bicyles:
print("2")
if 'redline' in bicyles:
print("3")
if语句处理列表
检查特殊元素
bicyles = ['trek', 'cannondale', 'redline', 'specialized', 'lu']
for bicyle in bicyles:
if bicyle == 'lu':
print("It is mine")
else:
print("No")
确定列表不是空
bicyles = []
if bicyles:
print("yes")
else:
print("no")
#输出
no
使用多个列表
bicyles = ['trek', 'cannondale', 'redline', 'specialized', 'lu']
bicyles2 = ['trek', 'hong', 'lu']
for bicyle in bicyles2:
if bicyle in bicyles:
print(bicyle + " yes")
else:
print(bicyle + " no")
设置if语句的格式