views:

447

answers:

5

I'm just getting into Python and I really like the terseness of the syntax. However; is there an easier way of writing an if-then statement so it fits on one line?

For example; say I have the simple test:

if count == N:
    count = 0
else:
    count = N + 1

is there a simpler way of writing this? I mean, in Objective-C I would write this as:

count = count == N ? 0 : count + 1;

Is there something similar for python?

Edit

I know that in this instance I can use count == (count + 1) % N. I'm asking about the general syntax.

+19  A: 

That's more specifically a ternary operator expression than an if-then, here's the python syntax

value_when_true if condition else value_when_false
cmsjr
+11  A: 
count = 0 if count == N else N+1

- the ternary operator. Although I'd say your solution is more readable than this.

Tim Pietzcker
@THC4k: Why the parentheses? They don't appear to be necessary and are not mentioned in PEP-308 or the docs (http://docs.python.org/reference/expressions.html#conditional-expressions)
Tim Pietzcker
Yeah, they are not necessary. Not sure where I picked up the habit - I thought it was suggested in PEP8, but I can't find it.
THC4k
OK, then I'll remove them again :)
Tim Pietzcker
@Tim Pietzcker I didn't just add parentheses, read the edit again. What you have now is a syntax error! You cannot assign in the statement, only this is valid: `count = 0 if count == N else N+1`. That's what the parentheses were supposed to tell you!
THC4k
Ahh. Sorry - now I see it. :) Thanks!
Tim Pietzcker
+4  A: 

General ternary syntax:

value_true if <test> else value_false

Another way can be:

[value_false, value_true][<test>]

e.g:

count = [0,N+1][count==N]
mshsayem
This counts on an implementation detail that `(False, True) == (0, 1)` which I don't know is guaranteed (but didn't check). And though terse, it isn't going to win any readability awards. You can also do `"abcdefg"[i]` in C, but it doesn't mean you should.
msw
@msw: It's guaranteed that `False == 0` and `True == 1`: no implementation detail here. :) See the 'Booleans' heading under http://docs.python.org/reference/datamodel.html#the-standard-type-hierarchy
Mark Dickinson
But aren't both values computed, no matter what [<test>] is?
tstenner
@msw: well, when it comes to ternary operations, I always prefer the first one. I just showed another possible way...
mshsayem
+2  A: 
<execute-test-successful-condition> if <test> else <execute-test-fail-condition>

with your code-snippet it would become,

count = 0 if count == N else N + 1
phoenix24
A: 
count = count == N ? 0 : count + 1;

Please don't do that; the next programmer to have to read your code will have a much harder time of it. "More space on screen" isn't the evil to avoid; "more time to read and understand" is the evil you should try to stomp out.

Dean J