码迷,mamicode.com
首页 > 编程语言 > 详细

Python if语句

时间:2018-12-21 00:02:35      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:示例   str1   white   style   没有   orange   int   class   语句   

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语句

标签:示例   str1   white   style   没有   orange   int   class   语句   

原文地址:https://www.cnblogs.com/liyunfei0103/p/10153045.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!