Using the question mark (?) for inline conditions

In JavaScript, you can code some conditional assignment by using “?”

var weather = temperature > 30 ? “Hot” : “cold”

It means that weather will be set to ‘hot’ if temperature > 30 is true, and to ‘cold’ if temperature > 30 is false.

You can find more here.

I think it’s a good idea to implement this feature in python, because it can help developers to code faster and have a lighter code.

The implementation may be (in my opinion) something like this (exactly the same as JavaScript) :

some_var = condition ? value_a : value_b

Good news! Guido used his time machine to add this in Python 2.5:

Moving this to the Help category, as this already exists: x = y if condition else z

Oh sorry i didn’t remember this one.
You are right.
But maybe there is something to do with the question mark?

1 Like