trinary operator - if then else

A

Alchemist

What is Python's version for the trinary if..then..else operator?

I want a one-liner such as
a?b:c
for the if..then..else control structure
if a
then b
else c

Does Python 2.4 support it?
 
M

Michael Bentley

What is Python's version for the trinary if..then..else operator?

I want a one-liner such as
a?b:c
for the if..then..else control structure
if a
then b
else c

Does Python 2.4 support it?

Not precisely, but you can *usually* get away with:

a and b or c
 
D

Diez B. Roggisch

Michael >>
Not precisely, but you can *usually* get away with:

a and b or c

This is really bad advice, as long as you don't explain why it "usually"
works (and often enough not). This for example won't work:
''

The reason is that the if-value has to be bool(v) == True, otherwise the
short-circuiting of the and will prevent the 0 from being returned.

So in general, _don't_ use this!

Diez
 
N

Nick Craig-Wood

Diez B. Roggisch said:
Michael >>

This is really bad advice, as long as you don't explain why it "usually"
works (and often enough not). This for example won't work:

''

You can use this if you want it to be bullet proof

(a and or [c])[0]

Not exactly elegant though!
 

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,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top