Two Ways to Return a Boolean in Python (and Why)

AI agents have made it easier than ever to get code that works. But there are many ways to write code that works. Every problem has more than one solution and every solution can be expressed in different ways. Here’s an example.

The Problem

The parameter weekday is True if it is a weekday, and the parameter vacation is True if we are on vacation. We sleep in if it is not a weekday or we’re on vacation. Return True if we sleep in.

Two Ways to Say the Same Thing

The solution can be found in the problem.

…not a weekday or we’re on vacation…

Add the word return at the beginning and remove the words “a,” “we’re,” and “on,” and you get:

def sleep_in(weekday, vacation): return not weekday or vacation

That’s the simplest and most obvious way to solve the problem. It returns the correct Boolean value in a single line. If I were to use this code in some alarm clock app, I’d probably rename it to can_sleep_in so that the name suggests that the function returns a Boolean.

The function can also be written like this:

def sleep_in(weekday, vacation): if not weekday or vacation: return True else: return False

It does the exact same thing in more lines, but it clearly shows when the function returns True and when it returns False. Writing functions this way makes them easier to read. The first solution can be read quickly but requires a bit of thought to understand. This function spells everything out.

The function also leaves room for more code. Sometimes a function is written as a placeholder or stub while other parts of the code are being written. That’s what this solution looks like to me.

Which One is Better?

The way you choose to write code depends on who is reading it and what it’s for. The shorter solution is ideal if you and the people you work with are comfortable with the Python language and proficient in programming. It also works if you just need to return the Boolean value. The longer solution works if you’re working with inexperienced Python programmers or you plan on adding more code later.

Get in touch

Questions, feedback, or just want to say hi? Send me an email.

Email me