Python if语句
1 简单示例
colors = ("red", "blue", "yellow", "orange", "white", "pink", "brown") for color in colors: if color == "blue": print("我喜欢蓝色") else: print(color.upper())
2 相等,不想等运算符
str1 = "abc" str2 = "ABC" print(str1 == str2) print(str1 != str2)
3 与和或用and和or
str1 = "abc" str2 = "ABC" print(str1 == "abc" and str2 == "ABC") print(str1 == "abc" or str2 == "BBC")
4 检查特定值是否包含或不包含在列表中
colors = ("red", "blue", "yellow", "orange", "white", "pink", "brown") print("red" in colors) print("green" not in colors)
5 if-elif-else
colors = ("red", "blue", "yellow", "orange", "white", "pink", "brown") for color in colors: if "red" == color: print(color + " 我喜欢") elif "blue" == color: print(color + " 我最喜欢") elif "green" == color: print(color + " 是春天的颜色") else: print(color + " 没感觉")
6 判断列表是否为空
# 列表中如果有元素,if语句为true colors = [] if colors: print("列表中有元素") else: print("列表中没有元素")