python else 用法总结

1. 常规的 if else 用法

x = True

if x:
    print 'x is true'
else:
    print 'x is not true'

2. if else 快捷用法

这里的 if else 可以作为三元操作符使用。

mark = 40
is_pass = True if mark >= 50 else False
print "Pass? " + str(is_pass)

3. 与 for 关键字一起用

在满足以下情况的时候,else 下的代码块会被执行:

# 打印 `For loop completed the execution`
for i in range(10):
    print i
else:
    print 'For loop completed the execution'

# 不打印 `For loop completed the execution`
for i in range(10):
    print i
    if i == 5:
        break
else:
    print 'For loop completed the execution'

4. 与 while 关键字一起用

和上面类似,在满足以下情况的时候,else 下的代码块会被执行:

# 打印 `While loop execution completed`
a = 0
loop = 0
while a <= 10:
    print a
    loop += 1
    a += 1
else:
    print "While loop execution completed"

# 不打印 `While loop execution completed`
a = 50
loop = 0
while a > 10:
    print a
    if loop == 5:
        break
    a += 1
    loop += 1
else:
    print "While loop execution completed"

5. 与 try except 一起用

try except 一起使用时,如果不抛出异常,else里的语句就能被执行。

file_name = "result.txt"
try:
    f = open(file_name, 'r')
except IOError:
    print 'cannot open', file_name
else:
    # Executes only if file opened properly
    print file_name, 'has', len(f.readlines()), 'lines'
    f.close()

参考文档