Ahmed Nuaman
Ahmed Nuaman

Reputation: 13261

Python shorthand conditional

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;

Upvotes: 18

Views: 18451

Answers (2)

Nice18
Nice18

Reputation: 566

Similar to JavaScript, you can use logical negation in Python. This uses the keyword not. One disadvantage of bool 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 get an unexpected value.

JavaScript

!!bar1

Python

not not bar1

Upvotes: 1

Fred Foo
Fred Foo

Reputation: 363767

Call bool on the object:

bool(bar1)

Upvotes: 33

Related Questions