Python if语句
Posted 云里飞
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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("列表中没有元素")
以上是关于Python if语句的主要内容,如果未能解决你的问题,请参考以下文章