How can I write an if-then-else statement in Python in one line? For example, I want a one-line version of the following:
if count == N:
count = 0
else:
count = N + 1
In Objective-C, I would write this as:
count = count == N ? 0 : count + 1;
In Python, you can use the ternary operator expression syntax to write an if-then-else statement in one line:
value_when_true if condition else value_when_false
For example:
'Yes' if fruit == 'Apple' else 'No'
This assigns 'Yes'
to the variable if fruit
is 'Apple'
, otherwise it assigns 'No'
.
With assignment:
fruit = 'Apple'
isApple = True if fruit == 'Apple' else False
This assigns True
to isApple
if fruit
is 'Apple'
, otherwise it assigns False
.
Contrasting with the if syntax:
fruit = 'Apple'
isApple = False
if fruit == 'Apple':
isApple = True
This accomplishes the same thing as the ternary operator expression but in a more verbose way.