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.
Adding to Madhuri ,
In Python, the shorthand syntax for the ternary operator is valid for actual values, including constants and functions. For example, you can use it like this:
'Yes' if fruit == 'Apple' else print('No Apple')
However, you cannot use it with keywords like raise
:
'Yes' if fruit == 'Apple' else raise Exception('No Apple')
This will result in a syntax error.
General ternary syntax in Python:
value_true if <test> else value_false
Another way to achieve the same result is using list indexing:
[value_false, value_true][<test>]
For example:
count = [0, N + 1][count == N]
Note that this evaluates both branches before choosing one. If you want to only evaluate the chosen branch, you can use lambda functions:
[lambda: value_false, lambda: value_true][<test>]()
For example:
count = [lambda: 0, lambda: N + 1][count == N]()