lundi 1 novembre 2021

Python ternary conditional operator returns unexpected value [closed]

I'm trying to make a one line expression return either a variable or a tuple of variables based on a condition. Example:

x = 1
y = 1
z = x if x == y else (x, y)

Expected result: z = 1. Actual result: z = (1, 1).

The regular if-else statement functions as expected and looks like this:

x = 1
y = 1

if x == y:
    z = x

else:
    z = (x, y)

Expected result: z = 1. Actual result: z = 1.

Am I misunderstanding the syntax or limitations of the expression?

Aucun commentaire:

Enregistrer un commentaire