Python If-Else on One Line

clear glass ball with box

In Python, you can have if-else statements on one line. This is possible by using what is called the “ternary operator” or conditional expression.

For instance, let’s say you have this regular if-else expression:

age = 20

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

print(age_group)

Output:

Adult

This works fine, but you can do the same if-else on one line of code:

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

print(age_group)

Output:

Adult

Be Careful with If-Else on One Line

Think twice before breaking your Python if-else on one line. This shorthand is meant to improve your code readability and make your code more concise.

Before using one-liner if-else statements, ask yourself a question: Does it improve your code readability? If the answer is no, don’t do it. Breaking lengthy if-else statements into one-liners can cause more harm than benefit.

I think the above example is good, but anything more complex than that should not be a one-liner.

Take a look at this example. Here is where one-liner if-else really complicates things. 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 take a look what happens when you compress this expression to one-liner:

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

Needless to say, this is impossible to read.

This is a perfect example of how using an one line if-else can really mess things up.

Conclusion

In Python, you can turn if-else statements into one-liner expressions using the ternary operator. This is adivced only if it can improve your code readability and overall quality.

Thanks for reading. Happy coding!

Further Reading

50 Python Interview Questions with Answers

50+ Buzzwords of Web Development

Share on facebook
Facebook
Share on google
Google+
Share on twitter
Twitter
Share on linkedin
LinkedIn
Share on pinterest
Pinterest

Leave a Comment

Your email address will not be published. Required fields are marked *