1

I'm currently transitioning from JavaScript to Python and I'm trying to understand if Python has something similar to the ternary operator as JavaScript does.

In JavaScript, I would write a ternary operation like this:

let a = 10;
let value = a > 5 ? 'Greater' : 'Lesser';
console.log(value); // Outputs: 'Greater'

This is very handy for writing compact conditional code. I'm trying to figure out if there's an equivalent in Python? If so, how would I rewrite the above JavaScript code snippet in Python?

I tried searching for "Python ternary operator", but the results I got were not very clear, especially when comparing it to JavaScript.

Could anyone provide a simple explanation and some examples of how to use the ternary operator in Python, if it exists?

I am expecting smooth tranisition

  • `value = 'Greater' if a > 5 else 'Lesser'` – Barmar Jul 31 '23 at 17:51
  • Note that "compact conditional code" is not necessarily good practice. Python did not have the ternary operator at all for a long time, because it often results in confusing and difficult-to-read code. One originally had to write `a > 5 and 'Greater' or 'Lesser'`, which still works but is ugly. – Tim Roberts Jul 31 '23 at 18:06
  • 1
    @TimRoberts It's worth pointing out that the old "hack" doesn't behave in the same way as a conditional expression if the `value_if_true` is falsy (`'', False, 0, (), ...`). – Danziger Jul 31 '23 at 18:18

1 Answers1

0

The syntax in Python is slightly diferent, and they are called conditional expressions:

[value_if_true] if [expression] else [value_if_false] 

Here's your example in Python:

a = 10
value = 'Greater' if a > 5 else 'Lesser'
print(value); # Outputs: 'Greater'
Danziger
  • 19,628
  • 4
  • 53
  • 83