Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Python by (47.6k 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 (106k 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
1 answer
asked Aug 26, 2019 in Python by Sammy (47.6k points)
0 votes
2 answers
0 votes
1 answer
+2 votes
1 answer

Browse Categories

...