search

Home  >  Q&A  >  body text

Understanding the ternary operator in Python [duplicate]

I'm currently transitioning from JavaScript to Python, and I'm wondering if Python has a ternary operator similar to JavaScript.

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

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

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

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

If it exists, can someone provide a simple explanation and some examples of how to use the ternary operator in Python?

I expect a smooth transition.

P粉877114798P粉877114798434 days ago840

reply all(1)I'll reply

  • P粉039633152

    P粉0396331522023-09-22 10:46:13

    The syntax in Python is slightly different, they are called Conditional expressions:

    [value_if_true] if [expression] else [value_if_false]

    Here is your Python example:

    a = 10
    value = 'Greater' if a > 5 else 'Lesser'
    print(value); # 输出:'Greater'

    reply
    0
  • Cancelreply