2.12 Ternary operator

Another conditional statement that allows you to control the flow of the program is ternary operator. Syntax:

There are three operands here. In the condition, we pass bool value. If the condition is true, then the statement1 is executed, otherwise statement2 is executed. Example:

Here we have a condition number1 > number2 which returns true or false. If the condition is true, then the value after the question mark (?) will be written to the result variable, otherwise value after colon (:).

Does anything remind you of a ternary operator? It’s a if/else statement🙂.

So the ternary operator is just shorthand for if/else. Example above using if/else looks like this:

Here we did without the result variable, but the ternary operator returns a value and it must be written to a variable.

Nested Ternary Operator

The ternary operator can be nested, as well as if/else statements:

With if/else statements, we could write it like this:


Previous article -> 2.11 if else Statements

Next article -> 2.13 Loops

Join to our community in Telegram — https://t.me/itifico

If you want to support me, you can buy me a cup of coffee and I will drink it when I write the next article :)

Donations list:

  1. Dinesh Chintalapudi — 3$
  2. Unknown — 5$
  3. Neisy — 3$
  4. Unknown — 3$



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store