How can we use Python Ternary Operator Without else?

If you want to convert a statement like −

if <condition>:

to a single line, You can use the single line if syntax to do so −

if <condition>: <some-code>

Another way to do this is leveraging the short-circuiting and operator like −

<condition> and <some-code>

If <condition> is false, then short-circuiting will kick in and the right-hand side won't be evaluated. If <condition> is true, then the right-hand side will be evaluated and <some-code> will be evaluated.

Updated on: 05-Mar-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started