问题
Is there any difference in the logic or performance of using the word and vs. the & symbol in Python?
回答1:
and is a Boolean operator. It treats both arguments as Boolean values, returning the first if it's falsy, otherwise the second. Note that if the first is falsy, then the second argument isn't even computed at all, which is important for avoiding side effects.
Examples:
False and True --> FalseTrue and True --> True1 and 2 --> 2False and None.explode() --> False(no exception)
& has two behaviors.
- If both are
int, then it computes the bitwise AND of both numbers, returning anint. If one isintand one isbool, then theboolvalue is coerced to int (as 0 or 1) and the same logic applies. - Else if both are
bool, then both arguments are evaluated and aboolis returned. - Otherwise a
TypeErroris raised (such asfloat & float, etc.).
Examples:
1 & 2 --> 01 & True --> 1 & 1 --> 1True & 2 --> 1 & 2 --> 0True & True --> TrueFalse & None.explode() --> AttributeError: 'NoneType' object has no attribute 'explode'
来源:https://stackoverflow.com/questions/32941097/are-and-and-equivalent-in-python