Python One Line Return if

Problem: How to return from a Python function or method in single line?

Example: Consider the following “goal” statement:

def f(x):
    return None if x == 0

However, this leads to a Syntax error:

In this tutorial, you’ll learn how to write the return statement with an if expression in a single line of Python code. You can get an overview of the three methods in the interactive code shell:

Exercise: The code has no output. Print the results of all three function executions for a given x. Is it always the same?

Let’s dive into the three methods.

Method 1: As a Multi-Liner

The following method is the standard and most Pythonic way to accomplish this but using multiple lines:

def f(x):
    if x==0:
        return None

But how to write this as a one-liner?

Method 2: Direct One-Liner If

Nothing simpler than that—just write it into a single line!

def f(x):
    if x==0: return None

I should note that PEP 8 is actually fine with writing if block statements into a single line. Nevertheless, the default return value of a function is None so the code does really nothing.

Method 3: Ternary Operator

If you look for something more Pythonic, you can check out the ternary operator (also called “conditional expression”):

def f(x):
    return None if x==0 else 42

In this case, you also have to define a return value for the value 42. You should read the statement like this:

return (None if x == 0 else 42)

The statement inside the parentheses returns either None or 42—depending on the condition x == 0. If it is True, the value None is returned. If it is False, the value 42 is returned.

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!