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;
Answers
In Python, you can use the ternary conditional expression to write an if-then-else
statement on a single line. The syntax is:
<expression_if_true> if <condition> else <expression_if_false>
For your example, you can write:
count = 0 if count == N else count + 1
This is Python's equivalent of the ternary operator in languages like C, C++, and Objective-C. It evaluates the condition (count == N
), and if it’s True
, it assigns 0
to count
; otherwise, it assigns count + 1
.