Coder Perfect

Putting a simple if-then-else statement on one line [duplicate]


I’m still learning Python, but I’m enjoying the brevity of the syntax. Is there a simpler method to write an if-then-else expression that fits on a single line?

For example:

if count == N:
    count = 0
    count = N + 1

Is there a more straightforward way of expressing this? In Objective-C, I’d write it like this:

count = count == N ? 0 : count + 1;

Is there anything comparable in Python?


I know I can use count == (count + 1) percent N in this situation.

I’m inquiring about the syntax in general.

Asked by Abizern

Solution #1

Here’s the python syntax for a ternary operator expression rather than an if-then.

value_when_true if condition else value_when_false

A Better Case Study: (thanks Mr. Burns)

‘Yes’ if fruit equals ‘Apple,’ otherwise ‘No.’

Now, compare and contrast assignment and if syntax.

fruit = 'Apple'
isApple = True if fruit == 'Apple' else False


fruit = 'Apple'
isApple = False
if fruit == 'Apple' : isApple = True

Answered by cmsjr

Solution #2

You can also use the “standard” if syntax and combine it into a single line with a colon.

if i > 3: print("We are done.")


field_plural = None
if field_plural is not None: print("insert into testtable(plural) '{0}'".format(field_plural)) 

Answered by Johannes Braunias

Solution #3

count = 0 if count == N else N+1

– the ternary operator. Although I’d say your solution is more readable than this.

Answered by Tim Pietzcker

Solution #4

General ternary syntax:

value_true if <test> else value_false

Another option is to:

[value_false, value_true][<test>]


count = [0,N+1][count==N]

This compares and contrasts both branches before deciding on one. To only look at the branch you’ve chosen:

[lambda: value_false, lambda: value_true][<test>]()


count = [lambda:0, lambda:N+1][count==N]()

Answered by mshsayem

Solution #5

<execute-test-successful-condition> if <test> else <execute-test-fail-condition>

It would become, with your code-snippet,

count = 0 if count == N else N + 1

Answered by phoenix24

Post is based on