Python 3, Are "else" statements needed?

I know that this seems trivial, but I don’t want to get into a bad habit.

The following 2 codes will output the same. Why should I bother to use an “else” statement if I can just return anything if the “if” condition is not met?

def in_range(num, lower, upper):
  if num >= lower and num <= upper:
    return True

  return False

print(in_range(10, 10, 10))
# should print True
print(in_range(5, 10, 20))
# should print False

Compared to:

def in_range(num, lower, upper):
  if num >= lower and num <= upper:
    return True
  else:
    return False

print(in_range(10, 10, 10))
# should print True
print(in_range(5, 10, 20))
# should print False

It depends on the logic and whether return is used in the branch. In the case above, it returns true on the first branch so it follows the else will return false. We don’t need the else, though since the line is not encountered if the line above it returns.

In the boolean type of situation such as this we don’t need an if either. Just return the evaluation of the logical expression.

return lower <= n <= upper

Does the exercise ask us to include upper in the range? If so, then the above is sufficient, if not then we change it slightly,

return lower <= num < upper

Notice that in Python we don’t need an AND expression. The inequality above is valid and works as expected.

6 Likes

Thank you for your answer! It has made things clearer.

2 Likes