If Else Statement in One Line in Python

You can write IF…ELSE statement in one line, but first, let’s check how it would look like in a standard statement.

car = 'Ford'

if car == 'Ford':



The code is quite good, but Python is designed to have syntax as concise as possible, so there is another way to write this statement. This time we will use something called the ternary operator, which was added to Python 2.5.

car = 'Ford'

print('Yes') if car == 'Ford' else print('No')

The result is the same as before, but this time the conditional statement is written in one line.


Explanation of the code:

While in the first, “normal” statement you can write the code as:
if the car is Ford then print ‘Yes’, otherwise print ‘No’.

The “one line” conditional statement can be read as:

Print ‘Yes’, unless the car is not Ford then print ‘No’.

This is an alternative that you can use in your code. If conditional statements become more complicated you would probably use the standard notation.