Operators in Python: Return Values of 'and' and 'or'
In Python, the operators 'and' and 'or' return one of their operands instead of solely returning boolean values. This behavior differs from the 'not' operator, which consistently returns a boolean value.
The 'and' operator evaluates to the first false value encountered in a sequence of operands. If no false value is found, it returns the last operand. Conversely, the 'or' operator evaluates to the first true value encountered in a sequence of operands. If no true value is found, it returns the last operand.
Examples:
>>> 0 or 42 42
In this example, '0' is false, while '42' is true. The 'or' operator returns the first true value encountered, which is '42'.
>>> 0 and 42 0
In this example, '0' is false, and '42' is true. The 'and' operator returns the first false value encountered, which is '0'.
Contrast with 'not':
The 'not' operator always returns a boolean value, either True or False. It flips the boolean value of its operand.
>>> not 0 True >>> not 42 False
This behavior ensures that the 'not' operator can be used for straightforward boolean negation.
以上がPython の「and」演算子と「or」演算子は何を返しますか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。