patternpythonCriticalCanonical
Putting a simple if-then-else statement on one line
Viewed 0 times
statementputtinglineelsesimpleonethen
Problem
How do I write an
For example, I want a one line version of:
In Objective-C, I would write this as:
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 + 1In Objective-C, I would write this as:
count = count == N ? 0 : count + 1;Solution
That's more specifically a ternary operator expression than an if-then, here's the python syntax
Better Example: (thanks Mr. Burns)
Now with assignment and contrast with if syntax
vs
value_when_true if condition else value_when_falseBetter 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 Falsevs
fruit = 'Apple'
isApple = False
if fruit == 'Apple' : isApple = TrueCode Snippets
value_when_true if condition else value_when_falsefruit = 'Apple'
isApple = True if fruit == 'Apple' else Falsefruit = 'Apple'
isApple = False
if fruit == 'Apple' : isApple = TrueContext
Stack Overflow Q#2802726, score: 2625
Revisions (0)
No revisions yet.