Python Boolean Statement

Possible Duplicate:
Ternary conditional operator in Python

I've programmed in Java for quite sometime, I'm learning Python in school and I remember in Java for a boolean expression you could do

boolean ? (if boolean is true this happens) : (if boolean is false this happens)

Is their a way to do the above Java code in Python? And what is the statement above properly called?


Yes, you can use this (more pythonic):

>>> "foo"'if condition else "bar"

Or, this (more common, but not recommended):

>>> condition and "foo" or "bar"

Yes, use a conditional expression:

somevalue if oneexpression else othervalue

Examples:

>>> 'foo' if True else 'bar'
'foo'
>>> 'foo' if False else 'bar'
'bar'

Before Python 2.5 where this was introduced, people used a combination of and and or expressions to achieve similar results:

expression and truevalue or falsevalue

but if the truevalue part of the expression itself evaluated to something that has the boolean value False (so a 0 or None or any sequence with length 0, etc.) then falsevalue would be picked anyway.


Python:

x if condition else y

Example:

val = val() if callable(val) else val
greeting = ("Hi " + name) if name != "" else "Howdy pardner"

This is often called "the ternary operator" because it has three operands. However, the term "ternary operator" applies to any operation with three operands. It just happens that most programming languages don't have any other ternary operators, so saying "the" is unambiguous. However, I'd call it the if/else operator or a conditional expression.

In Python, due to the way the and and or operators work, you can also use them in some cases for things you'd usually use the ternary operator for in C-derived languages:

# provide a default value if user doesn't enter one
name = raw_input("What is your name? ") or "Jude"
print "Hey", name, "don't make it bad."

# call x only if x is callable
callable(x) and x()
链接地址: http://www.djcxy.com/p/7408.html

上一篇: 从徒弟到专家

下一篇: Python布尔语句