# 判断语句 ## 基本用法 判断,基于一定的条件,决定是否要执行特定的一段代码,例如判断一个数是不是正数: In [1]: ```py x = 0.5 if x > 0: print "Hey!" print "x is positive" ``` ```py Hey! x is positive ``` 在这里,如果 `x > 0` 为 `False` ,那么程序将不会执行两条 `print` 语句。 虽然都是用 `if` 关键词定义判断,但与**C,Java**等语言不同,**Python**不使用 `{}` 将 `if` 语句控制的区域包含起来。**Python**使用的是缩进方法。同时,也不需要用 `()` 将判断条件括起来。 上面例子中的这两条语句: ```py print "Hey!" print "x is positive" ``` 就叫做一个代码块,同一个代码块使用同样的缩进值,它们组成了这条 `if` 语句的主体。 不同的缩进值表示不同的代码块,例如: `x > 0` 时: In [2]: ```py x = 0.5 if x > 0: print "Hey!" print "x is positive" print "This is still part of the block" print "This isn't part of the block, and will always print." ``` ```py Hey! x is positive This is still part of the block This isn't part of the block, and will always print. ``` `x < 0` 时: In [3]: ```py x = -0.5 if x > 0: print "Hey!" print "x is positive" print "This is still part of the block" print "This isn't part of the block, and will always print." ``` ```py This isn't part of the block, and will always print. ``` 在这两个例子中,最后一句并不是`if`语句中的内容,所以不管条件满不满足,它都会被执行。 一个完整的 `if` 结构通常如下所示(注意:条件后的 `:` 是必须要的,缩进值需要一样): ```py if : elif : else: ``` 当条件1被满足时,执行 `if` 下面的语句,当条件1不满足的时候,转到 `elif` ,看它的条件2满不满足,满足执行 `elif` 下面的语句,不满足则执行 `else` 下面的语句。 对于上面的例子进行扩展: In [4]: ```py x = 0 if x > 0: print "x is positive" elif x == 0: print "x is zero" else: print "x is negative" ``` ```py x is zero ``` `elif` 的个数没有限制,可以是1个或者多个,也可以没有。 `else` 最多只有1个,也可以没有。 可以使用 `and` , `or` , `not` 等关键词结合多个判断条件: In [5]: ```py x = 10 y = -5 x > 0 and y < 0 ``` Out[5]: ```py True ``` In [6]: ```py not x > 0 ``` Out[6]: ```py False ``` In [7]: ```py x < 0 or y < 0 ``` Out[7]: ```py True ``` 这里使用这个简单的例子,假如想判断一个年份是不是闰年,按照闰年的定义,这里只需要判断这个年份是不是能被4整除,但是不能被100整除,或者正好被400整除: In [8]: ```py year = 1900 if year % 400 == 0: print "This is a leap year!" # 两个条件都满足才执行 elif year % 4 == 0 and year % 100 != 0: print "This is a leap year!" else: print "This is not a leap year." ``` ```py This is not a leap year. ``` ## 值的测试 **Python**不仅仅可以使用布尔型变量作为条件,它可以直接在`if`中使用任何表达式作为条件: 大部分表达式的值都会被当作`True`,但以下表达式值会被当作`False`: * False * None * 0 * 空字符串,空列表,空字典,空集合 In [9]: ```py mylist = [3, 1, 4, 1, 5, 9] if mylist: print "The first element is:", mylist[0] else: print "There is no first element." ``` ```py The first element is: 3 ``` 修改为空列表: In [10]: ```py mylist = [] if mylist: print "The first element is:", mylist[0] else: print "There is no first element." ``` ```py There is no first element. ``` 当然这种用法并不推荐,推荐使用 `if len(mylist) > 0:` 来判断一个列表是否为空。