0 votes
1 view
in Python by (40.4k points)
edited by

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.

1 Answer

0 votes
by (92.9k points)
  • We have a short way of writing if-else in Python, Here’s the syntax:-

value_when_true if condition else value_when_false

  • Example:-

'Yes' if grade == 'D' else 'No' 

  • Another way you can do is:-

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

  • You can also do it with Ternary operator:-

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

Related questions

0 votes
1 answer
0 votes
2 answers
+2 votes
1 answer
0 votes
0 answers
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...