How do I write an if
-then
-else
statement in Python so that it fits on one line?
For example, I want a one line version of:
if count == N:
count = 0
else:
count = N + 1
In Objective-C, I would write this as:
count = count == N ? 0 : count + 1;
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
Better Example: (thanks Mr. Burns)
'Yes' if fruit == 'Apple' else 'No'
Now with assignment and contrast with if syntax
fruit = 'Apple'
isApple = True if fruit == 'Apple' else False
vs
fruit = 'Apple'
isApple = False
if fruit == 'Apple' : isApple = True