Python学习笔记(4)-if语句

来源:互联网 发布:java中else是什么意思 编辑:程序博客网 时间:2024/04/28 19:05

(和java大同小异,写法上稍有不同,可对比着记忆)

条件测试

相等和不等

代码:

car = 'bmw'  #赋值语句print(car == 'bmw')  #判断语句,判断是否相等,相等返回True,不等返回False

结果:

True

(PS: 需要注意相比字符串的大小写,python对大小写敏感)

不等的判断为!=
代码:

car = 'bmw'print(car != 'bssw')

结果:

True

数字除了是否相等外还有有大小的比较

符号有=,>,>=,<,<=
代码:

age = 18print(age == 18)print(age > 18)print(age >= 18)print(age < 18)print(age <= 18)

结果:

TrueFalseTrueFalseTrue    

检查多个条件

  • 使用and 检查(左右两个条件都成立返回True,否则返回False)
  • 使用or 检查(左右两个条件只要有一个成立返回True,否则返回False)

代码:

my_age = 18your_age = 60print(my_age <= 30 and your_age <= 30)print(my_age <= 30 or your_age <= 30)

结果:

FalseTrue

检查特定值是否包含在列表中

  • in
  • not in

代码:

pets = ['dog', 'cat', 'fox']print('dog' in pets)print('dog' not in pets)

结果:

TrueFalse

布尔表达式

boolean值只能为True 或者 False,赋值即可

can_read = True

if语句

  • 简单的if语句
  • if-else语句
  • if-elif-else语句

代码:

age = 18if age >= 18:    print("Adult")age = 17if age >= 18:    print("Adult")else:    print("Young")age = 2if age >= 18:    print("Adult")elif age <= 5:  #注意是elif,和java不同    print("Baby")else:    print("Young")

结果:

AdultYoungBaby

if语句处理列表

代码:

foods = ['bread', 'meat', 'milk', 'tomato']for food in foods:    if food == 'meat':  #判断语句        print(food + " is not enough")    else:        print(food + "is added")

结果:

breadis addedmeat is not enoughmilkis addedtomatois 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.
0 0