Python if condition in one line

Python If-Else on One Line

In Python, you can have if-else statements on one line.

To write an if-else statement on one line, follow the conditional expression syntax:

some_expression if condition else other_expression
age = 20 # One-liner if-else statement age_group = "Minor" if age < 18 else "Adult" print(age_group)

This is handy with short if-else statements because it allows you to save lines of code while preserving code quality.

Turning longer if-else statements into one-liners can make your code unreadable.

In this guide, you are going to learn how to turn if-else statements into one-liner expressions in Python. More importantly, you are going to learn how to do it wisely.

If you are interested in learning other Python tips and “tricks”, feel free to read this article.

One Line If-Else Statements in Python

Writing a one-line if-else statement in Python is possible by using the ternary operator, also known as the conditional expression.

Here is the syntax of the one-liner ternary operator:

some_expression if condition else other_expression

For instance, let’s say you have an if-else statement that checks if a person is an adult based on their age:

This works just fine. But you can get the job done by writing the if-else statement as a neat one-liner expression.

age = 20 age_group = "Minor" if age < 18 else "Adult" print(age_group)

As you can see, you were able to save three lines of code without sacrificing the code readability.

One Line If-Elif-Else in Python

Fitting everything in one line is not good practice. More importantly, a Python code line should not exceed 80 characters in general.

This is why Python does not support the if-elif-else statements as one-liner expressions.

If you really want to push it, you can chain ternary conditional operators to achieve the if-elif-else behavior:

n = 10 a = 1 if n < 10 else 2 if n >10 else 0

But please, do not do this. As you can see from the above, it only makes the code less readable.

It is way cleaner to write the above expression like this:

n = 10 if n < 10: a = 1 elif n >10: a = 2 else: a = 0

Some people do not use one-liner if-else statements at all. This is because it is up to a debate as to whether it improves code quality or not.

Be Careful with If-Else on One Line

One-line if-else statements should only be used with simple expressions (identifiers, literals, and operators). They should not be used with longer statements.

This is to preserve the readability and expressibility of the code. So think twice before breaking your Python if-else on one line.

Читайте также:  Music player for html

You already saw a bad example of a lengthy one-liner if-elif-else statement in the previous section. Let’s see a bad example of a one-liner if-else statement as well.

First, let’s use a regular if-else approach:

x = 1 if x % 2 == 0: result = x * 2 + 10 else: result = x / 2 - 10

This looks clear. If x is even, multiply it by 2 and add 10 to it. If the number is odd, divide it by 2 and subtract 10.

But let’s then take a look at what happens when you turn it into a one-liner expression:

result = x * 2 + 10 if x % 2 == 0 else x / 2 - 10

Total chaos. Nobody wants to read code like this.

This is a perfect example of how using one line if-else can mess things up. So be smart!

Conclusion

In Python, you can turn if-else statements into one-liner expressions using the ternary operator (conditional expression).

Using the ternary conditional operator in Python follows this syntax:

some_expression if condition else other_expression

As an example, you can perform a simple age check with a shorthand if-else statement:

age = 12 age_group = "Minor" if age < 18 else "Adult"

Using a one-liner if-else statement makes sense if it improves the code quality. But it can work against you if you write complex statements as one-liners.

Thanks for reading. Happy coding!

Источник

How to Write the Python if Statement in one Line

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:

The is the code that evaluates to either True or False . If this code evaluates to True, then the code below (represented by ) 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).

Читайте также:  Http запрос авторизация php

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 : elif : # executes only if expression_01 is False elif : # . 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:

As you can see, not much has changed. We simply need to “pull” the indented line 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:

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:

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:

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:

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

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:

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

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!

Источник

Оцените статью