| Monument ( @ 2002-10-15 12:44:00 |
Python ternary operator
I really want to record a very minor epiphany of last night about Python. For a good while I've wanted something like the C operator
or, very usefully:
or even, for printing,
Well, in Python (as in C), truth is represented by the number one, and falsehood by the number zero. So you can represent
How cool is that?
I really want to record a very minor epiphany of last night about Python. For a good while I've wanted something like the C operator
?: (known as the "ternary operator" because it's the only one which considers three things). For the uninitiated, this gives you one result if something's true, and another if it isn't. For example:(the_user_wants_an_apple?number_of_apple s:number_of_oranges)or, very usefully:
(number==1?"kibbutz":"kibbutzim")or even, for printing,
(user_is_logged_in?"":"You might want to log in, by the way.")Well, in Python (as in C), truth is represented by the number one, and falsehood by the number zero. So you can represent
?: by giving a list with two things in (which, traditionally, are number 0 and number 1) and then choosing the member of the list corresponding to the condition. So['kibbutzim', 'kibbutz'][number==1]How cool is that?