jb.
jb.

Reputation: 10341

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?

Upvotes: 7

Views: 1400

Answers (2)

Scott Lawrence
Scott Lawrence

Reputation: 7243

On the null-coalescing operator in C#, what you have in the question isn't a correct usage. That would fail at compile time.

In C#, the correct way to write what you're attempting would be this:

trait = this.trait == this.spouse.trait ? self.trait : defaultTrait

Null coalesce in C# returns the first value that isn't null in a chain of values (or null if there are no non-null values). For example, what you'd write in C# to return the first non-null trait or a default trait if all the others were null is actually this:

trait = this.spouse.trait ?? self.trait ?? defaultTrait;

Upvotes: 1

Greg Hewgill
Greg Hewgill

Reputation: 992947

Yes, you can write:

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

This is called a Conditional Expression in Python.

Upvotes: 15

Related Questions