If you are writing a function, then return a value. Do not use print (that is for debugging only). Once you use return
, you can return early if you do find the author:
def author_name(lines):
'''Finds the authors name within the docstring'''
for line in lines:
name = 'Unknown'
if line.startswith("Author"):
line = line.strip('\n')
line = line.strip('\'')
author_line = line.split(': ')
if len(author_line[1]) >=4:
name = author_line[1]
return "{0:21}{1}".format("Author", name) # ends the function, we found an author
return "{0:21}{1}".format("Author", name)
print(author_name(some_docstring.splitlines()))
The last return
statement only executes if there were no lines starting with Author
, because if there was, the function would have returned early.
Alternatively, because we default name
to Unknown
, you can use break
as well to end the loop early and leave returning to that last line:
def author_name(lines):
'''Finds the authors name within the docstring'''
for line in lines:
name = 'Unknown'
if line.startswith("Author"):
line = line.strip('\n')
line = line.strip('\'')
author_line = line.split(': ')
if len(author_line[1]) >=4:
name = author_line[1]
break # ends the `for` loop, we found an author.
return "{0:21}{1}".format("Author", name)