How to do "new_variable = (variable) ? True : False;" (php) on python?

D

Daniel Crespo

Hello to all,

How can I do

new_variable = (variable) ? True : False;

in Python in one line?

I want to do something like this:

dic = {'item1': (variable) ? True-part : False-part}

Any suggestions?

Daniel
 
S

Sam Pointon

Daniel said:
Hello to all,

How can I do

new_variable = (variable) ? True : False;

in Python in one line?

I want to do something like this:

dic = {'item1': (variable) ? True-part : False-part}

Any suggestions?

Daniel

There's a trick using the short-circuiting boolean logic operators to
emulate the ternary operator in Python. Basically, you do
TEST and TRUE_PART or FALSE_PART

However, this fails if TRUE_PART evaluates to a False value; you end up
with FALSE_PART's value instead.

This is a trick/hack, though, and shouldn't really be used much - use
an if statement instead, or wait til 2.5 when an if expression is
coming in.
 
S

Scott David Daniels

new_variable = variable

Of course to answer your actual question:

new_variable = variable and True or False

But you should consider that Peter has given
you a better answer than you think.

<yoda>
Don't try to force everything to the type you expect,
use things as they are; embrace duck-typing.
</yoda>
:)

--Scott David Daniels
(e-mail address removed)
 
D

Dave Hansen

<yoda>
Don't try to force everything to the type you expect,
use things as they are; embrace duck-typing.
</yoda>

Wrong, the grammar you have.
Do not Everything to the type you expect force.
Do or do not, there is no try.
Things as they are use.
Duck-typing embrace.

Ditto. Regards,
-=Dave
 
B

bonono

Peter said:
new_variable = variable

:)

I would assume the OP is just lazy and don't want to type :

new_variable = (variable_is_true_value) ?
some_expression_when_variable_is_true_value is true :
some_expression_when_variable_is_true_value is false

rather than simple True/False.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top