Understanding return True and False in Python

What does return True/False actually do in Python? I’ve added a sample code below to provide context for my question. I often see programs with if statements that return True or False, but what exactly is happening here? Why wouldn’t you just use a print statement to display True or False? I’m a bit confused.

def false(x, y):
    x > y
    return False

false(9, 10)

Could someone clarify the concept behind using return True python instead of just printing values?

The reason for using return True/False in Python instead of just printing values is that you’ll often want the function’s result to be used elsewhere in your program, not just displayed. By returning a value, the function becomes more versatile—it can calculate something, and the caller can decide what to do with the result: print it, store it, or use it in another operation. This is an example of composability in programming.

Your example doesn’t work as expected because it evaluates x > y but doesn’t do anything with that result before returning False. Here’s a corrected example:

def is_greater(x, y):  
    if x > y:  
        return True  
    else:  
        return False  

Now, you can use the is_greater function in any context:

x = is_greater(9, 10)  
print(x)  # This will print False  

Using return true python in this way allows you to reuse the function wherever you need it, instead of limiting its output to a print statement.

Building on Netra’s point, you can make this function even simpler by directly returning the boolean expression instead of explicitly checking the condition with if and else. Python allows you to write concise, elegant code like this:

def is_greater(x, y):  
    return x > y  

Here, the comparison x > y itself evaluates to True or False, so there’s no need for an explicit check. This approach achieves the same result in fewer lines, making it more readable.

For example:

print(is_greater(9, 10))  # Prints False  
print(is_greater(15, 10))  # Prints True  

By using return true python in this way, you’re making your code cleaner while retaining the flexibility to use the function in different contexts.

Emma’s approach is great for simplicity, but sometimes you might want to add a bit more logic or control to how you return the result. For instance, you can use a ternary expression for cases where you want to customize what happens when the condition is met or not:

def is_greater(x, y):  
    return True if x > y else False  

While this approach is more verbose, it provides flexibility for extending the function. For example, if you later want to log something or perform additional operations, it’s easier to do so.

Here’s how it works:

print(is_greater(20, 10))  # Returns True  
print(is_greater(5, 15))   # Returns False  

This use of return true python keeps your code organized and allows for easy modifications without altering the overall logic.