Ternary/inline if Expressions – Python

The ternary operator is a concise way to express conditional statements in programming languages.

Ternary Operator in Javascript

In javascript ternary operators typically looks like this:

  • The condition is evaluated first. If it is true, the expression returns the value_if_condition_is_true.
  • If the condition is false, the expression returns the value_if_condition_is_false.

In python we can use inline if blocks alternative to javascirpt-ternary operator.

Inline If Expression in Python

In above, this expression returns “x” value if the condition is true, otherwise it returns to y.

Here is a simple example:

In above, we defined state variable that typed bool and we assigned True. To determine de result’s value, code blocks evaluates condition (if state is True) first if state is true, expression returns “passed”.

Simple Example of Inline If expressions

There is a exampla that divide two number:

  • if number_2 is not equal to 0 function returns division of number
  • if number_2 is equal to zero function returns None.


Using ternary operators provides Conciseness, Code Performance, Reduced Nesting, Readability when they used correctly.

ibrahim tunc
ibrahim tunc
Articles: 13

Leave a Reply

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