HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonCriticalCanonical

Putting a simple if-then-else statement on one line

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
statementputtinglineelsesimpleonethen

Problem

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;

Solution

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

Code Snippets

value_when_true if condition else value_when_false
fruit = 'Apple'
isApple = True if fruit == 'Apple' else False
fruit = 'Apple'
isApple = False
if fruit == 'Apple' : isApple = True

Context

Stack Overflow Q#2802726, score: 2625

Revisions (0)

No revisions yet.