Programming
python conditional-operator
Updated Sat, 23 Jul 2022 02:28:25 GMT

Python version of C#'s conditional operator (?)


I saw this question but it uses the ?? operator as a null check, I want to use it as a bool true/false test.

I have this code in Python:

if self.trait == self.spouse.trait:
    trait = self.trait
else:
    trait = defualtTrait

In C# I could write this as:

trait = this.trait == this.spouse.trait ? this.trait : defualtTrait;

Is there a similar way to do this in Python?




Solution

Yes, you can write:

trait = self.trait if self.trait == self.spouse.trait else defaultTrait

This is called a Conditional Expression in Python.