27 julio, 2024

How does the ternary operator work in Python? | Bootcamps

Well, in Python and any other language that has such an operator. In reality, the ternary operator is more commonly called conditional expression in Python.

This is a shortened version of an expression if, which fits on a single line. It should be used for very simple situations and in no case should it be abused. When in doubt, use a if normal.

Let’s look at an example, first with a if normal and then with the equivalent conditional expression (ternary operator):

x = 43 if x == 42: result = ‘is the answer’ else: result = ‘you were close to him’

The structure of a conditional expression is as follows:

if else

Therefore, if the previous code were rewritten with a ternary operator (conditional expression), it would look like this:

x = 43 result = ‘is the answer’ if x == 42 else ‘you were close to him’ result # will contain ‘you were close to him’

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *