Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 843
jb. Avatar asked Oct 07 '11 19:10

jb.


People also ask

What is C in Python?

The C function always has two arguments, conventionally named self and args. The self argument points to the module object for module-level functions; for a method it would point to the object instance. The args argument will be a pointer to a Python tuple object containing the arguments.

Can Python run C?

The python default implementation is written in C programming and it's called CPython. So it's not very uncommon to use C functions in a python program. In this tutorial, we learned how to easily call C functions in a python program.

Is Python 3 written in C?

Python is written in C (actually the default implementation is called CPython).

Is Python built on top of C?

Interpreted languages like Python, Ruby, and PHP have their primary implementations written in C. It is even used by compilers for other languages to communicate with the machine.


2 Answers

Yes, you can write:

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

This is called a Conditional Expression in Python.

like image 54
Greg Hewgill Avatar answered Oct 31 '22 13:10

Greg Hewgill


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;
like image 21
Scott Lawrence Avatar answered Oct 31 '22 12:10

Scott Lawrence