How to write an if-else statement in one line

Asked 1 years ago, Updated 1 years ago, 109 views

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

Is there any way to write this code in one line?

In object-C,

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

We could have shared it, but I don't know exactly what that is called.

syntax python if-else

2022-09-22 22:17

1 Answers

? :Writing together is called a trinomial operator.

Python also has a trinomial operator, but the order is a little different from that of C-based languages, so it will be a little confusing when you first use it for the first time.

The triad operator syntax in python: value_when_true if condition else value_when_false

For example, if the object-C's trinomial operator was like this

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

Python's trigonometric operator is

count = 0 if (count == N) else count + 1;

Do you see the difference?


2022-09-22 22:17

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.