if 条件语句
if 是 Python 中最基础的分支结构。它根据条件的真假,决定是否执行某段代码。Python 的 if 不需要括号包裹条件,也不需要大括号包裹代码块——用缩进来表示从属关系。
基本语法
x = 10
if x > 0:
print "x is positive"
if 后面跟一个布尔表达式,以冒号 : 结尾。下一行开始,缩进 4 个空格的代码块属于 if 分支。如果条件为真,执行缩进块;如果为假,跳过整个缩进块,继续执行后面的代码。
x = -5
if x > 0:
print "x is positive" # 不会执行
print "Done" # 会执行
真值判断
if 的条件不一定是布尔值。Python 会调用内置的 bool() 函数将条件转换为布尔值:
if 42: # True,非零数字为真
print "yes"
if "hello": # True,非空字符串为真
print "yes"
if [1, 2]: # True,非空列表为真
print "yes"
if 0: # False,零为假
print "no" # 不执行
if "": # False,空字符串为假
print "no" # 不执行
if []: # False,空列表为假
print "no" # 不执行
Python 2 中的假值包括:None、False、0、0L、0.0、0j、""、u""、[]、()、{}、set()。其余皆为真值。
比较操作
条件中常用比较运算符:
age = 25
if age >= 18:
print "Adult"
name = "Alice"
if name == "Alice":
print "Hello, Alice"
if name != "Bob":
print "You are not Bob"
注意 == 和 is 的区别:== 比较值,is 比较身份(内存地址):
a = [1, 2, 3]
b = [1, 2, 3]
if a == b:
print "Values are equal" # 执行
if a is b:
print "Same object" # 不执行
复合条件
用 and、or、not 组合多个条件:
score = 85
attendance = 0.9
if score >= 60 and attendance >= 0.8:
print "Pass"
if score < 60 or attendance < 0.8:
print "Warning"
if not (score < 60):
print "At least passed"
and 和 or 使用短路求值:
# and:第一个为假就停止,返回第一个操作数
result = 0 and 1/0 # 返回 0,不会触发除零错误
# or:第一个为真就停止,返回第一个操作数
result = 1 or 1/0 # 返回 1,不会触发除零错误
嵌套 if
if 可以嵌套,但嵌套过深会降低可读性。PEP 8 建议尽量扁平化:
x = 15
# 嵌套写法
if x > 0:
if x < 20:
print "x is between 0 and 20"
# 更清晰的写法
if x > 0 and x < 20:
print "x is between 0 and 20"
# 或者用链式比较(Python 特有)
if 0 < x < 20:
print "x is between 0 and 20"
链式比较 0 < x < 20 等价于 0 < x and x < 20,但更简洁、更易读。
缩进的重要性
Python 用缩进来表示代码块,这是语法的一部分,不是风格建议。缩进不一致会导致 IndentationError:
if x > 0:
print "positive"
print "still positive" # IndentationError:缩进不一致
同一个代码块中的所有行必须有完全相同的缩进(推荐 4 个空格)。混用 Tab 和空格是 Python 2 中最隐蔽的 bug 来源之一。