Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
like image 405
Ahmed Nuaman Avatar asked Jul 07 '11 09:07

Ahmed Nuaman


People also ask

What is shorthand If statement in Python?

Shorthand If and If Else in Python Shorthand if and if else is nothing but a way to write the if statements in one line when we have only one statement to execute in the if block and the else block.

Is there ?: In Python?

In fact, the ?: operator is commonly called the ternary operator in those languages, which is probably the reason Python's conditional expression is sometimes referred to as the Python ternary operator.

How do you write a conditional statement in Python?

The statement can be a single line or a block of code. #If the condition is true, the statement will be executed. num = 5 if num > 0: print(num, "is a positive number.") print("This statement is true.") #When we run the program, the output will be: 5 is a positive number. This statement is true.


1 Answers

Call bool on the object:

bool(bar1)
like image 173
Fred Foo Avatar answered Oct 11 '22 03:10

Fred Foo