一个古怪而又有用的python语法

我们在使用python的for语句时一般都是这样写的(以查找文件为例):

import os
dirs = os.listdir('.')
found = False
for d in dirs:
    if d == 'test.txt':
        found = True
        break
if not found:
    #do something
    print 'not found'



其实,也可以这么写:

 

import os
dirs = os.listdir('.')
for d in dirs:
    if d == 'text.txt':
        break
else:
    #do something
    print 'not found'


少了一个要作标识的过程,使程序简单了不少

 

你可能感兴趣的:(python)