Python for else 语法有点特别,在其它的编程语言中是没有这种语法结构,其语法结构如下:
for x in sequence:
statement1
statement2
...
statementN
else:
else_statement1
else_statement2
...
else_statementN
看到语法结构我们很好理解了,它在原有for循环的基础上加上else语法,当for跳出循环的时候会同时执行else里面的代码块。举例说明Python for else 语法:
#!/usr/bin/python
# coding=utf-8
for i in range(3):
print('i = ', i)
else:
print('输出完毕')
程序输出结果:i = 0
i = 1
i = 2
输出完毕
i = 1
i = 2
输出完毕