Note that you need to be able to return a false entry in case it loops all the way down without finding anything. However, you do not want to break out of the for loop if nothing found in one subdirectory without checking the next sub directory. The return will break out of the function, returning the results without having to enter a break.
def search_file(path):
Initialize results to no file found
val = False
sub = None
for name in os.listdir(path):
sub = os.path.join(path, name)
val = os.path.isfile(sub):
if val:
return val, sub #And break recursion
else:
#check the subdirectory.
val, sub = search_file(sub)
# Break out if a valid file was found.
if val:
return val, sub
# No files found for this directory, return a failure
return val, sub
On the other hand, if you want to have only one return, you can use a break as follows
def search_file(path):
Initialize results to No file found
val = False
sub = None
for name in os.listdir(path):
sub = os.path.join(path, name)
val = os.path.isfile(sub):
if val:
break # break out of the for loop and return
else:
#check the subdirectory.
val, sub = search_file(sub)
# Break out if a valid file was found.
if val:
break
# Return the True or False results
return val, sub