Back to articles list Articles
7 minutes read

How to Write the Python if Statement in one Line

Have you ever heard of writing a Python if statement in a single line? Here, we explore multiple ways to do exactly that, including using conditional expressions in Python.

The if statement is one of the most fundamental statements in Python. In this article, we learn how to write the Python if in one line.

The if is a key piece in writing Python code. It allows developers to control the flow and logic of their code based on information received at runtime. However, many Python developers do not know they may reduce the length and complexity of their if statements by writing them in a single line.

For this article, we assume you’re somewhat familiar with Python conditions and comparisons. If not, don’t worry! Our Python Basics Course will get you up to speed in no time. This course is included in the Python Basics Track, a full-fledged Python learning track designed for complete beginners.

We start with a recap on how Python if statements work. Then, we explore some examples of how to write if statements in a single line. Let’s get started!

How the if Statement Works in Python

Let’s start with the basics. An if statement in Python is used to determine whether a condition is True or False. This information can then be used to perform specific actions in the code, essentially controlling its logic during execution.

The structure of the basic if statement is as follows:

if <expression>:
    <perform_action>

The <expression> is the code that evaluates to either True or False. If this code evaluates to True, then the code below (represented by <perform_action>) executes.

Python uses whitespaces to indicate which lines are controlled by the if statement. The if statement controls all indented lines below it. Typically, the indentation is set to four spaces (read this post if you’re having trouble with the indentation).

As a simple example, the code below prints a message if and only if the current weather is sunny:

weather = "sunny"
if weather == "sunny":
    print("I should take a walk outside!")
# output:
# I should take a walk outside!

The if statement in Python has two optional components: the elif statement, which executes only if the preceding if/elif statements are False; and the else statement, which executes only if all of the preceding if/elif statements are False. While we may have as many elif statements as we want, we may only have a single else statement at the very end of the code block.

Here’s the basic structure:

if <expression_01>:
    <perform_action_01>
elif <expression_02>:  # executes only if expression_01 is False
    <perform_action_02>
elif <expression_03>:
    <perform_action_03>

#  ... Add as many "elifs" as you want

else:  # executes only if all expressions above are False
    

Here’s how our previous example looks after adding elif and else statements. Change the value of the weather variable to see a different message printed:

weather = "sunny"

if weather == "sunny":
    print("I should take a walk outside!")
elif weather == "cloudy":
    print("I'm not sure it will rain. Maybe I will take a walk?")
elif weather == "rainy":
    print("It is raining. I will stay at home.")
else:
    print("I don't know what the weather is...")

# output:
# I should take a walk outside!

How to Write a Python if in one Line

Writing an if statement in Python (along with the optional elif and else statements) uses a lot of whitespaces. Some people may find it confusing or tiresome to follow each statement and its corresponding indented lines.

To overcome this, there is a trick many Python developers often overlook: write an if statement in a single line!

Though not the standard, Python does allow us to write an if statement and its associated action in the same line. Here’s the basic structure:

if : 

As you can see, not much has changed. We simply need to “pull” the indented line <perform_action> up to the right of the colon character (:). It’s that simple!

Let’s check it with a real example. The code below works as it did previously despite the if statement being in a single line. Test it out and see for yourself:

weather = "sunny"

if weather == "sunny": print("I should take a walk outside!")

# output:
# I should take a walk outside!

Writing a Python if Statement With Multiple Actions in one Line

That’s all well and good, but what if my if statement has multiple actions under its control? When using the standard indentation, we separate different actions in multiple indented lines as the structure below shows:

if <expression>:
    <perform_action_01>
    <perform_action_02>
    <perform_action_03>

Can we do this in a single line? The surprising answer is yes! We use semicolons to separate each action in the same line as if placed in different lines.

Here’s how the structure looks:

if <expression>: <perform_action_01>; <perform_action_02>; <perform_action_03>

And an example of this functionality:

weather = "sunny"

if weather == "sunny": print("It's sunny."); print("I should take a walk outside!"); print("The sun is very warm.")

# output:
# It's sunny.
# I should take a walk outside!
# The sun is very warm.

Have you noticed how each call to the print() function appears in its own line? This indicates we have successfully executed multiple actions from a single line. Nice!

By the way, interested in learning more about the print() function? We have an article on the ins and outs of the print() function.

Writing a Full Python if/elif/else Block Using Single Lines

You may have seen this coming, but we can even write elif and else statements each in a single line. To do so, we use the same syntax as writing an if statement in a single line.

Here’s the general structure:

if <expression_01>: 
elif <expression_02>: 
elif <expression_03>: 
else : <perform_another_action>

Looks simple, right? Depending on the content of your expressions and actions, you may find this structure easier to read and understand compared to the indented blocks.

Here’s our previous example of a full if/elif/else block, rewritten as single lines:

weather = "sunny"

if weather == "sunny": print("I should take a walk outside!")
elif weather == "cloudy": print("I'm not sure it will rain. Maybe I will take a walk?")
elif weather == "rainy": print("It is raining. I will stay at home.")
else: print("I don't know what the weather is...")

# output:
# I should take a walk outside!

Using Python Conditional Expressions to Write an if/else Block in one Line

There’s still a final trick to writing a Python if in one line. Conditional expressions in Python (also known as Python ternary operators) can run an if/else block in a single line.

A conditional expression is even more compact! Remember it took at least two lines to write a block containing both if and else statements in our last example.

In contrast, here’s how a conditional expression is structured:

value = <value_if_true> if <expression> else <value_if_false>

The syntax is somewhat harder to follow at first, but the basic idea is that <expression> is a test. If the test evaluates to True, then <value_if_true> is the result. Otherwise, the expression results in <value_if_false>.

As you can see, conditional expressions always evaluate to a single value in the end. They are not complete replacements for an if/elif/else block. In fact, we cannot have elif statements in them at all. However, they’re most helpful when determining a single value depending on a single condition.

Take a look at the code below, which determines the value of is_baby depending on whether or not the age is below five:

age = 8

if age < 5:
    is_baby = True
else:
    is_baby = False

print(is_baby)

# output:
# False

This is the exact use case for a conditional expression! Here’s how we rewrite this if/else block in a single line:

age = 8
is_baby = True if age < 5 else False

print(is_baby)

# output:
# False

Much simpler!

Go Even Further With Python!

We hope you now know many ways to write a Python if in one line. We’ve reached the end of the article, but don’t stop practicing now!

If you do not know where to go next, read this post on how to get beyond the basics in Python. If you’d rather get technical, we have a post on the best code editors and IDEs for Python. Remember to keep improving!