一个简单的if-else条件判断,要注意if和else后面别忘了加冒号。
animal = 'cat'
if animal == 'cat':
print('it is a cat')
else:
print('it is not a cat')
检查多个条件
与关系
使用关键字and将两个条件测试合并来表示与的关系。
age = 18
if age>=16 and age <=20:
print("yes")
else:
print("no")
yes
或关系
使用关键字or将两个条件测试合并来表示或的关系。
age_1 = 18
age_2 = 15
if age_1>16 or age_2>16:
print("yes")
else:
print("no")
yes
检查特定值是否在列表中
要判断特定的值是否在列表中可使用关键字in。
animals = ['cat','dog','lion']
print('cats' in animals)
True
要判断特定的值是否不在列表中可使用关键字 not in。
animals = ['cat','dog','lion']
print('cat' not in animals)
False
判断列表不是空的
if语句中将列表名用在条件表达式中时,Python将在列表至少包含一个元素时返回True,在列表为空时返回False。
animals = []
if animals:
print('Not empty')
else:
print('Empty')
Empty