syntax for -c cmd

Paul McGuire ptmcg at austin.rr._bogus_.com
Wed May 10 18:35:27 EDT 2006


"James" <hslee911 at yahoo.com> wrote in message
news:1147284798.136873.237730 at i40g2000cwc.googlegroups.com...
> Wrong syntax is shown below. What should be the delimiter before else?
>
> python -c 'if 1==1: print "yes"; else print "no"'
>
> James
>

So you can approximate this same logic with a boolean expression:

print (1==1 and "yes" or "no")

This is because Python short-circuits boolean and's and or's, and returns
the last evaluated value.  So the expanded logic here is:
evaluate 1==1 -> True
evaluate "yes" -> True - we are done, return "yes"

if the expression were (math.pi==3 and "yes" or "no"), we would get:
evaluate math.pi==3 -> False
(skip evaluation of "yes", first part failed so go straight to or term)
evaluate "no" -> well, doesn't matter if this is True or False, it's the
last thing we have to evaluate, return it

Generally this gets idiomatically expressed as:

(condition and trueConditionValue or falseConditionValue)


This is currently (Python 2.4) the closest Python gets to C's ternary
operator.  Note that there are some risks, for example, this rendition
*wont* work.

numberOfApples = 1
print "I have %d apple%s" % ( numberOfApples, (numberOfApples ==1 and "" or
"s"))

This is because "" evaluates boolean-ly to False, so the conditional
conjunction of (numberOfApples==1) and "" is False, so we continue to
evaluate the expression, and wind up printing  "I have 1 apples".

The resolution is to invert the test:
numberOfApples = 1
print "I have %d apple%s" % ( numberOfApples, (numberOfApples !=1 and "s" or
""))

(If I have zero of something, I prefer to say "I have 0 somethings" - if you
like to say "I have 0 something" then make the test read (numberOfApples > 1
and "s" or "") )

In the coming 2.5 version of Python, there is a ternary-like expression:

numberOfApples = 1
print "I have %d apple%s" % ( numberOfApples, ("" if numberOfApples ==1 else
"s"))

Python 2.5 is still in preliminary releases though, and will not be
generally available until this coming fall.  This will allow you to spell
out if-then-else conditions on the command line.  In general scripting,
though, compaction of code into one-liners is not always considered a
virtue.  This code:

print "I have %s apple%s" % (numberOfApples==0 and "no" or numberOfApples,
numberOfApples !=1 and "s" or "")

will not win you points with your software maintenance team.

-- Paul





More information about the Python-list mailing list