Skip to content
Fix Code Error

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

March 13, 2021 by Code Error
Posted By: Anonymous

I’m just getting into Python and I really like the terseness of the syntax. However, is there an easier way of writing an if–then–else statement so it fits on one line?

For example:

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

Is there a simpler way of writing this? I mean, in Objective-C I would write this as:

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

Is there something similar for Python?

Update

I know that in this instance I can use count == (count + 1) % N.

I’m asking about the general syntax.

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
Answered By: Anonymous

Related Articles

  • Can't install via pip because of egg_info error
  • How different is Objective-C from C++?
  • PHP parse/syntax errors; and how to solve them
  • What's the difference between eval, exec, and compile?
  • Calculate the mean by group
  • How do I include certain conditions in SQL Count
  • Reference — What does this symbol mean in PHP?
  • data.table vs dplyr: can one do something well the other…
  • How do I call Objective-C code from Swift?
  • Julia - Understanding JuMP Gurobi outputs

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

How to download a file from server using SSH?

Next Post:

Vertically align text within a div

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • Get code errors & solutions at akashmittal.com
© 2022 Fix Code Error