tags:

views:

405

answers:

6

If I have some code like:

x = foo ? 1 : 2

How should I translate it to Python? Can I do this?

if foo:
  x = 1
else:
  x = 2

Will x still be in scope outside the if / then blocks? Or do I have to do something like this?

x = None
if foo:
  x = 1
else:
  x = 2
A: 

You could use something like:

val = float(raw_input("Age: "))
status = ("working","retired")[val>65]
print "You should be",status

though it is not very pythonic

(the other options are closer to C/PERL, but this involves more tuple magic)

Manuel Ferreria
+21  A: 

Use the ternary operator(formally conditional expression) in Python 2.5+.

x = 1 if foo else 2
phihag
Only, please call it the conditional expression, since that's what it is.
S.Lott
@Adriano Varoli Piazza @S.Lott added that to the answer. Thanks!
phihag
+1  A: 

Duplicate of this one.

I use this (although I'm waiting for somebody to downvote or comment if it is incorrect):

x = foo and 1 or 2
jonstjohn
That works in this case, but it can be dangerous in general: x = foo and bar or bazwill produce baz if foo is true and bar is false, which probably isn't what you want.
Khoth
ah, got it. I've used this for a while, and wasn't quite sure why it wasn't an accepted method. I can see that now.
jonstjohn
+5  A: 

The Ternary operator mentioned is only available from Python 2.5. From the WeekeePeedeea:

Though it had been delayed for several years by disagreements over syntax, a ternary operator for Python was approved as Python Enhancement Proposal 308 and was added to the 2.5 release in September 2006.

Python's ternary operator differs from the common ?: operator in the order of its operands; the general form is op1 if condition else op2. This form invites considering op1 as the normal value and op2 as an exceptional case.

Before 2.5, one could use the ugly syntax (lambda x:op2,lambda x:op1)[condition]() which also takes care of only evaluating expressions which are actually needed in order to prevent side effects.

Adriano Varoli Piazza
A: 

A nice python trick is using this:

foo = ["ifFalse","ifTrue"][booleanCondition]

It creates a 2 membered list, and the boolean becomes either 0 (false) or 1 (true), which picks the correct member. Not very readable, but pythony :)

I would neither readable, nor pythonic, but it's still something I use all the time... if you're doing this trick, do it as a tuple: (trueFunc, falseFunc)[bool(condition)]
Gregg Lind
The Python 2.5 conditional expression will evaluate only ONE of the trueFunc, falseFunc expressions. This formula evaluates both.
George V. Reilly
Use (booleanCondition and [trueFunc] or [falseFunc])[0].
ThomasH
A: 

I'm still using 2.4 in one of my projects and have come across this a few times. The most elegant solution I've see for this is:

x = {True: 1, False: 2}[foo is not None]

I like this because it represents a more clear boolean test than using a list with the index values 0 and 1 to get your return value.

adam