# 判断语句¶

## 基本用法¶

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

Hey!
x is positive


print "Hey!"
print "x is positive"


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 <condition 1>:
<statement 1>
<statement 2>
elif <condition 2>:
<statements>
else:
<statements>



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个，也可以没有。

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

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中使用任何表达式作为条件：

• 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.