Python if-then-else in one line example

Posted on March 2, 2020 at 12:52 pm

You can put if-then-else in one line in Python like this:

value_when_true if condition else value_when_false

Here is a quick example:

'Yes' if color == 'Blue' else 'No'

Here is an example using assignment and contrast:

color = 'Blue'
isBlue = True if color == 'Blue' else False

Here is an example using a function:

def is_error(data):
   return True if data.get('error') else False
 
print(is_error(data))

And here is the “traditional” if syntax:

if i > 3: print("Do something.")

Receive updates via email

Other Posts

Updated Posts