Python one line if statements are equivalent to Ternary operators. These are conditional expressions that evaluate the input based on a condition. Creating python liners is a great science I should say and it’s all fun. In this article let’s look at creating beautiful python one line if statements using different methods.

Example – Python one line if statements

Writing one line if the statement is not only fun but also it increases the compactness of the code and readability as well. If you want to write an if statement in one line, that to without an else statement, just write if statement without else.

Let’s see how it works!

condition = True 
if condition: print('HackAnons')

HackAnons

But note that, this method will violate the PEP8 standards which read ‘no multiple statements in a single line’. It’s hard to say but you cannot consider this a python code though.

Throw away else branch

In this method, you are free to use Ternary operators. As stated above ternary operators are just conditional expressions that work on the condition. But, don’t worry, you can throw away the else statement by not assigning value to a variable.

condition = True
print('HackAnons') if condition else None

HackAnons

Perfect. you can write the python one line if statement using ternary operator. Anyway, you can throw the else out of the context. You are free to replace None with any dummy. Doesn’t matter.

Ternary with Dummy assignment

If you want to assign a value to variable and without else, do this.

condition  = True
x= 10 if condition else None 

In this method, we will be using ternary with a dummy value. If the condition is not met, then the else value i.e. None will be assigned to the variable. As simple as that.

Short circuiting

This method is one of the widely used and I love this. In this method, the logical and operator will return the second value if the first is True.

condition = True
condition and print('HackAnons')

HackAnons

As I said, in this case, the first condition is true. So the logical and operator returned the second value i.e. HackAnons.

Key Points | Python one line if statements

  • You can use ternary operator for expressions and not for statements.
  • You can not able to use if-elif-else statement in single line.
  • Ternary = Condition – Then – Else.
  • You can execute only one function using if-else block.
  • Using ternary always is not a good idea. Sometimes it may get complex and affect readability. So use it in a smart way.

Ending Note

Ternary operators can be more useful in writing one-liner code in python. You can easily write one line if statements in python as shown above. There are considerably four methods using which you can make the process easy. That’s all for now. Happy Python!!!.

Categorized in:

Tagged in: