判断语句

基本用法

判断,基于一定的条件,决定是否要执行特定的一段代码,例如判断一个数是不是正数:

In [1]:
x = 0.5
if x > 0:
    print "Hey!"
    print "x is positive"
Hey!
x is positive

在这里,如果 x > 0False ,那么程序将不会执行两条 print 语句。

虽然都是用 if 关键词定义判断,但与C,Java等语言不同,Python不使用 {}if 语句控制的区域包含起来。Python使用的是缩进方法。同时,也不需要用 () 将判断条件括起来。

上面例子中的这两条语句:

print "Hey!"
    print "x is positive"

就叫做一个代码块,同一个代码块使用同样的缩进值,它们组成了这条 if 语句的主体。

不同的缩进值表示不同的代码块,例如:

x > 0 时:

In [2]:
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."
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]:
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."
This isn't part of the block, and will always print.

在这两个例子中,最后一句并不是if语句中的内容,所以不管条件满不满足,它都会被执行。

一个完整的 if 结构通常如下所示(注意:条件后的 : 是必须要的,缩进值需要一样):

if <condition 1>:
    <statement 1>
    <statement 2>
elif <condition 2>: 
    <statements>
else:
    <statements>

当条件1被满足时,执行 if 下面的语句,当条件1不满足的时候,转到 elif ,看它的条件2满不满足,满足执行 elif 下面的语句,不满足则执行 else 下面的语句。

对于上面的例子进行扩展:

In [4]:
x = 0
if x > 0:
    print "x is positive"
elif x == 0:
    print "x is zero"
else:
    print "x is negative"
x is zero

elif 的个数没有限制,可以是1个或者多个,也可以没有。

else 最多只有1个,也可以没有。

可以使用 andor , not 等关键词结合多个判断条件:

In [5]:
x = 10
y = -5
x > 0 and y < 0
Out[5]:
True
In [6]:
not x > 0
Out[6]:
False
In [7]:
x < 0 or y < 0
Out[7]:
True

这里使用这个简单的例子,假如想判断一个年份是不是闰年,按照闰年的定义,这里只需要判断这个年份是不是能被4整除,但是不能被100整除,或者正好被400整除:

In [8]:
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."
This is not a leap year.

值的测试

Python不仅仅可以使用布尔型变量作为条件,它可以直接在if中使用任何表达式作为条件:

大部分表达式的值都会被当作True,但以下表达式值会被当作False

  • False
  • None
  • 0
  • 空字符串,空列表,空字典,空集合
In [9]:
mylist = [3, 1, 4, 1, 5, 9]
if mylist:
    print "The first element is:", mylist[0]
else:
    print "There is no first element."
The first element is: 3

修改为空列表:

In [10]:
mylist = []
if mylist:
    print "The first element is:", mylist[0]
else:
    print "There is no first element."
There is no first element.

当然这种用法并不推荐,推荐使用 if len(mylist) > 0: 来判断一个列表是否为空。