else语句
Python中,可以在while和for循环中使用else语句。
在循环中使用时,else语句只在循环完成后执行,也就是说__break语句也会跳过else块__。
举例:查找一个数的最大约数
#!/usr/bin/env python
def showMaxFactor(num):
count = num / 2
while count > 1:
if num % count == 0:
print 'largest factor of %d is %d' % (num, count)
break
count -= 1
else:
print num, "is prime"
for eachNum in range(10, 21):
showMaxFactor(eachNum)
摘自《Python核心编程》

浙公网安备 33010602011771号