(和java大同小异,写法上稍有不同,可对比着记忆)
条件测试
相等和不等
代码:
car = 'bmw' #赋值语句
print(car == 'bmw') #判断语句,判断是否相等,相等返回True,不等返回False
结果:
True
(PS: 需要注意相比字符串的大小写,python对大小写敏感)
不等的判断为!=
代码:
car = 'bmw'
print(car != 'bssw')
结果:
True
数字除了是否相等外还有有大小的比较
符号有=
,>
,>=
,<
,<=
代码:
age = 18
print(age == 18)
print(age > 18)
print(age >= 18)
print(age < 18)
print(age <= 18)
结果:
True
False
True
False
True
检查多个条件
- 使用
and
检查(左右两个条件都成立返回True,否则返回False) - 使用
or
检查(左右两个条件只要有一个成立返回True,否则返回False)
代码:
my_age = 18
your_age = 60
print(my_age <= 30 and your_age <= 30)
print(my_age <= 30 or your_age <= 30)
结果:
False
True
检查特定值是否包含在列表中
- in
- not in
代码:
pets = ['dog', 'cat', 'fox']
print('dog' in pets)
print('dog' not in pets)
结果:
True
False
布尔表达式
boolean值只能为True
或者 False
,赋值即可
can_read = True
if语句
- 简单的if语句
- if-else语句
- if-elif-else语句
代码:
age = 18
if age >= 18:
print("Adult")
age = 17
if age >= 18:
print("Adult")
else:
print("Young")
age = 2
if age >= 18:
print("Adult")
elif age <= 5: #注意是elif,和java不同
print("Baby")
else:
print("Young")
结果:
Adult
Young
Baby
if语句处理列表
代码:
foods = ['bread', 'meat', 'milk', 'tomato']
for food in foods:
if food == 'meat': #判断语句
print(food + " is not enough")
else:
print(food + "is added")
结果:
breadis added
meat is not enough
milkis added
tomatois added
确定列表不是空的
foods = []
if foods: #在列表有值的时候返回True,空的时候返回False
print("There's something.")
else:
print("blank")
结果:
blank
提示:if sth:
中,只要sth
不是数字0,其他非零数字,非空列表,非空字典,非空字符串等都符合该条件
使用多个列表
代码:
now_foods = ['meat', 'mile', 'tomato', 'bread'] #现有的食物
request_foods = ['watermelon', 'mile', 'pear', 'bread'] #需要的食物
for request_food in request_foods:
if request_food in now_foods: #每个需要的食物都到现有的食物中去判断是否存在
print(request_food + " is added.")
else:
print(request_food + " is not enough.")
结果:
watermelon is not enough.
mile is added.
pear is not enough.
bread is added.