Python shorthand conditional

Question:

Here’s a quick one…

In Python one can do:

foo = foo1 if bar1 else foo2

And that’s cool, but how can I just get a True or False without having to write

foo = True if bar1 else False

For example, in JS you can forcibly cast a boolean type by doing

var foo = !!bar1;
Asked By: Ahmed Nuaman

||

Answers:

Call bool on the object:

bool(bar1)
Answered By: Fred Foo

Similar to JavaScript, you can use logical negation in Python. This uses the keyword not. One disvantage of bool function is you can change its value as this is not a reserved word. If bool variable’s value is not callable. For example, bool = 7, an error will be raised. If bool variable’s value is callable. For example, bool = int, you may not get your expected value.

JavaScript

!!bar1

Python

not not bar1
Answered By: Nice18
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.