Early return
It can often be useful to return early from a function. This is particularly useful when you are checking whether something is true or false. As soon as you discover it is true (or false), you can return with your answer.
Check if a string has a digit in it
This example checks if a string has a digit in it:
def has_digit(text):
"""Returns true if any character in `text` is a digit"""
for char in text:
if char.isdigit():
return True
return False
We loop through every character in the input text
, checking if it is a digit. As soon as we find one digit, we return True
. If we never find a digit, we return False
. This means that the for
loop doesn’t finish executing if we find a digit. That is OK! This is how early return works.
So if we run has_digit('abcdefg123')
, this will return True
as soon as the for
loop gets to 1
. If we run has_digit('a few words')
, this will return False
.
Check if any line contains BYU
This example checks if any line in a list of lines contains BYU:
def has_byu(lines):
"""Returns True if any of the lines contain the text 'BYU'"""
for line in lines:
if 'BYU' in line:
return True
return False
Check if a string is entirely digits
We don’t always return True
when we return early. If we are proving something is False
, we can likewise return early as soon as we discover it is False
. This example checks if a string is entirely digits:
def all_digits(text):
"""Returns True if all of the characters are digits"""
for c in text:
if not c.isdigit():
return False
return True