How to return a boolean in Python

Master returning booleans in Python. We cover various methods, pro tips, real-world examples, and how to fix common bugs.

How to return a boolean in Python
Published on: 
Tue
Apr 21, 2026
Updated on: 
Wed
Apr 22, 2026
The Replit Team

Python functions often return a boolean value to signal success or failure. This simple True or False output is crucial for control flow and decisions in your code.

In this article, you'll learn several techniques to return booleans. You'll also find practical tips, see real-world applications, and get debugging advice so you can write cleaner, more effective Python code.

Basic function returning a boolean

def is_positive(number):
return number > 0

result = is_positive(5)
print(result)--OUTPUT--TRUE

The is_positive function shows the most direct way to return a boolean. The comparison expression number > 0 itself evaluates to either True or False. The function simply returns this resulting boolean value without needing any extra logic.

This technique is more concise than using a verbose if/else block to handle the return. By returning the outcome of the comparison operator directly, your code becomes cleaner and more readable—a common and efficient pattern in Python for functions that perform a simple check.

Common boolean return patterns

That direct comparison is just one of several common patterns; you can also use logical operators and built-in functions to return booleans.

Using comparison operators to return booleans

def compare_values(a, b):
return a == b, a != b, a > b, a < b, a >= b, a <= b

print(compare_values(5, 3))--OUTPUT--(False, True, True, False, True, False)

The compare_values function shows how you can return multiple boolean results at once. Python evaluates each comparison expression individually and then packs the boolean outcomes into a single tuple. This is a handy way to get a comprehensive set of checks from one function call.

  • == (equal to)
  • != (not equal to)
  • > (greater than) and < (less than)
  • >= (greater than or equal to) and <= (less than or equal to)

Using logical operators for boolean results

def check_conditions(age, has_license):
return age >= 18 and has_license

print(check_conditions(19, True))
print(check_conditions(19, False))--OUTPUT--True
False

The check_conditions function shows how logical operators can build more complex boolean checks. The and operator requires that both conditions—age >= 18 and has_license—are True for the function to return True. If either condition is false, the entire expression evaluates to False.

  • and: Returns True only if all conditions are true.
  • or: Returns True if at least one condition is true.
  • not: Inverts a boolean value, turning True into False and vice versa.

Using Python's built-in boolean functions

def check_data(collection):
return any(collection), all(collection), bool(collection)

print(check_data([True, False, True]))
print(check_data([]))--OUTPUT--(True, False, True)
(False, True, False)

Python's built-in functions provide a quick way to evaluate collections like lists. The check_data function uses three of these to inspect the provided data.

  • any() checks if at least one item in the collection is truthy.
  • all() checks if every item is truthy. For an empty collection, it returns True.
  • bool() evaluates the collection itself, returning False if it's empty and True otherwise.

This is why an empty list [] returns (False, True, False)—it has no truthy items, all of its (zero) items are technically truthy, and the list itself is empty.

Advanced boolean techniques

Building on those foundational patterns, you can also embed boolean logic within class methods, lambda functions, and custom objects using the __bool__ method.

Class methods returning boolean values

class User:
def __init__(self, name, age):
self.name = name
self.age = age

def is_adult(self):
return self.age >= 18

user = User("Alice", 25)
print(user.is_adult())--OUTPUT--TRUE

You can embed boolean logic directly into your classes. In the User class, the is_adult method checks the object's own age attribute to see if the user is 18 or older. This approach encapsulates the logic within the class itself, making your code more organized and readable.

  • This keeps state-specific checks tied directly to the object they describe.

Calling user.is_adult() runs this check on that specific instance, returning True or False based on its unique data.

Using lambda functions for boolean returns

is_even = lambda x: x % 2 == 0
is_in_range = lambda x, min_val, max_val: min_val <= x <= max_val

print(is_even(4), is_even(7))
print(is_in_range(5, 1, 10))--OUTPUT--True False
True

lambda functions offer a concise way to create small, single-expression functions without a formal def statement. They're perfect for simple boolean logic that you need on the fly.

  • The is_even lambda checks if a number is divisible by two.
  • The is_in_range lambda uses a chained comparison to see if a value falls between a minimum and maximum.

This pattern is especially useful when you need a quick, disposable function, like for sorting or filtering data based on a simple condition.

Custom boolean evaluation with __bool__

class Account:
def __init__(self, balance):
self.balance = balance

def __bool__(self):
return self.balance > 0

account = Account(100)
print(bool(account))
empty_account = Account(0)
print(bool(empty_account))--OUTPUT--True
False

The __bool__ dunder method lets you define what makes an instance of your class evaluate to True or False. In the Account class, this method returns True only if the account's balance is greater than zero, giving your objects a natural boolean behavior.

  • When you use an object in a context that requires a boolean, like calling bool(account), Python automatically calls your custom __bool__ method to determine its truthiness based on its internal state.

Move faster with Replit

Learning these individual techniques is the first step. The next is combining them into a complete application. Replit is an AI-powered development platform where you can do just that, instantly. It comes with all Python dependencies pre-installed, so you can skip the setup and start coding right away.

Instead of just piecing together functions, you can use Agent 4 to build a full product from a simple description. The Agent handles writing the code, connecting to databases, managing APIs, and even deploying your app. For example, you could describe an app that uses boolean logic to:

  • Build a form validator that uses checks like is_adult() or is_in_range() to confirm user inputs are valid before submission.
  • Create a data-cleaning utility that uses any() or all() to scan datasets for rows with missing values and flag them for review.
  • Develop a simple access control system that uses a function like check_conditions() to grant or deny entry based on multiple boolean flags.

Simply describe your app, and Replit will write the code, test it, and fix issues automatically, all within your browser.

Common errors and challenges

While returning booleans is straightforward, a few common pitfalls can trip you up if you're not careful.

Avoiding the if return True/False anti-pattern

A frequent mistake is writing an explicit if/else statement just to return True or False. This pattern is redundant because the comparison expression itself already evaluates to the exact boolean you need.

Instead of writing if condition: return True else: return False, you can simply use return condition. This approach is more direct, reduces clutter, and is considered more idiomatic in Python.

Handling None values in boolean functions

Functions that might return None require careful handling in boolean checks. A value of None is not the same as False, and trying to use it in a comparison, like if my_variable > 10:, will raise a TypeError.

To prevent these runtime errors, always check for None explicitly before performing other operations. A simple guard like if my_variable is not None: makes your function's behavior more predictable and robust.

Beware of falsy values in boolean expressions

Python has a concept of "falsy" values, which can sometimes lead to subtle bugs. In a boolean context, values like 0, an empty string "", an empty list [], and None all evaluate to False.

This becomes a problem when a falsy value is also a valid one. For instance, if a user's account balance is 0, a simple check like if balance: would incorrectly evaluate to False. To avoid this, be specific in your checks, such as if balance is not None:, to correctly handle valid data that happens to be falsy.

Avoiding the if return True/False anti-pattern

It’s common to see explicit if/else statements used to return True or False. While this works, it’s unnecessarily verbose. The comparison expression itself already evaluates to a boolean, so the extra logic is redundant. Take a look at the following example.

def is_adult(age):
if age >= 18:
return True
else:
return False

print(is_adult(20))

The is_adult function works, but it takes the long way around. Since the expression age >= 18 already results in True or False, you can return its value directly. Check out the refactored version below.

def is_adult(age):
return age >= 18

print(is_adult(20))

The refactored is_adult function is more concise because it returns the result of the comparison age >= 18 directly. This expression already evaluates to True or False, so an if/else block isn't needed. This pattern is cleaner and considered more idiomatic in Python. Keep an eye out for this opportunity when writing simple check functions. It’s a quick way to improve readability and reduce code length.

Handling None values in boolean functions

When a function returns None, you can't use its output in a direct comparison. Because None has no numerical value, Python can't evaluate an expression like number > 0 and raises a TypeError. See what happens in the following example.

def is_positive(number):
return number > 0

print(is_positive(5))
print(is_positive(None)) # Will raise TypeError

The is_positive(None) call triggers the TypeError because the function directly attempts the invalid comparison None > 0. To make your function robust, you need to check for None first. See how to implement this check below.

def is_positive(number):
if number is None:
return False
return number > 0

print(is_positive(5))
print(is_positive(None))

The updated is_positive function now safely handles None values. By adding the check if number is None: return False, you catch None before it can cause a TypeError during the comparison. This makes your function more robust and its behavior predictable.

  • Keep an eye out for this issue when your function receives data from external sources like databases or APIs, where None often indicates a missing value.

Beware of falsy values in boolean expressions

Python treats certain values like 0 and empty strings as "falsy," meaning they evaluate to False in boolean checks. This can cause your function to fail unexpectedly when a falsy value is actually a valid input you need to process.

Take a look at the code below to see this in action.

def validate_user_input(value):
if value:
return True
return False

print(validate_user_input("hello"))
print(validate_user_input(""))
print(validate_user_input(0)) # Returns False for legitimate input

The validate_user_input function returns False for 0 and "" because the if value: check treats any falsy value as invalid. This is a problem when those are legitimate inputs. See how to write a more precise check below.

def validate_user_input(value):
if isinstance(value, str) and value != "":
return True
elif isinstance(value, (int, float)):
return True
return False

print(validate_user_input("hello"))
print(validate_user_input(""))
print(validate_user_input(0))

The updated validate_user_input function fixes the issue by being more specific than a simple if value: check. It uses isinstance() to verify the data type, which allows it to correctly identify 0 as valid input while rejecting an empty string "".

  • This precision is crucial when validating user forms or processing data where falsy values are legitimate.

Real-world applications

With these techniques and error-handling patterns in mind, you can build practical features like a validate_input function or a can_access permission check.

Using validate_input functions for form validation

Boolean-returning functions are perfect for validating user input, ensuring data like a username or password adheres to specific rules before you accept it.

def validate_username(username):
return len(username) >= 3 and username.isalnum()

def validate_password(password):
has_length = len(password) >= 8
has_uppercase = any(char.isupper() for char in password)
has_digit = any(char.isdigit() for char in password)
return has_length and has_uppercase and has_digit

print(validate_username("user123"))
print(validate_password("Password123"))
print(validate_password("password"))

The validate_username function uses the and operator to enforce two rules at once. It returns True only if the username is at least three characters long and is alphanumeric. The validate_password function demonstrates a more complex validation by breaking its logic into separate boolean variables for readability.

  • It uses any() with a generator expression to efficiently check for at least one uppercase letter and one digit.
  • The final return statement combines these checks, ensuring all conditions must be met for the password to be valid.

Building a permission system with the can_access function

Boolean logic is also perfect for building a permission system, where a function like can_access can check multiple conditions to grant or deny access with a single True or False.

class Resource:
def __init__(self, name, owner, is_public=False):
self.name = name
self.owner = owner
self.is_public = is_public

class User:
def __init__(self, user_id, role):
self.user_id = user_id
self.role = role

def can_access(user, resource):
if resource.is_public:
return True
if user.user_id == resource.owner:
return True
if user.role == "admin":
return True
return False

admin = User("admin1", "admin")
bob = User("bob", "viewer")
private_doc = Resource("Finances", "alice", False)
public_doc = Resource("Guidelines", "alice", True)

print(can_access(admin, private_doc))
print(can_access(bob, private_doc))
print(can_access(bob, public_doc))

The can_access function determines access rights by evaluating a sequence of rules. It returns True as soon as any condition is satisfied, which makes the logic efficient since it doesn't need to check every rule.

  • First, it checks if the resource.is_public.
  • Then, it verifies if the user.user_id matches the resource.owner.
  • Finally, it checks if the user.role is "admin".

If none of these conditions pass, the function defaults to returning False. This pattern provides a clear, cascading set of checks where access is denied unless explicitly granted.

Get started with Replit

Now, turn these boolean patterns into a real tool. Give Replit Agent a prompt like “build a form validator for user sign-ups” or “create a file access checker based on user roles.”

The Agent writes the code, tests for errors, and deploys your app directly from your browser. Start building with Replit.

Get started free

Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.

Get started free

Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.