The question naturally arises as to which expressions are deemed to be true and which
false. Naturally, for the special Python logic items named True and False (often referred to
as Boolean values) the answer is obvious. Also, the logical states of truth and falsehood
that result from conditional checks like ‘Is x greater than 5?’ or ‘Is y in this list?’ are also
clear. However, in Python even expressions that do not involve an obvious query can be
assigned a status of conditional truthfulness; the value of an item itself can be forced to be
considered as either True or False inside an if statement. For example, when tested in a
conditional statement the number 1 will be interpreted as being True and the number 0 as
False, although their values are otherwise numeric. For the Python built-in data types
discussed in this chapter the following are deemed to be False in such a context:
None # nothingness
False # False Boolean
0 # 0 integer
0.0 # 0.0 floating point
"" # empty string
() # empty tuple
[] # empty list
{} # empty dictionary
set(()) # empty set
frozenset(()) # empty frozen set
And everything else is deemed to be True in a conditional context.
Python has the standard comparison (or relational) operators:
x > y # x greater than y?
x < y # x less than y?
x >= y # x greater than or equal to y?
x <= y # x less than or equal to y?
x == y # x equal to y?
x != y # x not equal to y?
In terms of syntax, in Python 2 you can compare anything with anything, although if
the expressions are not of the same data type the result is rather meaningless in some
sense. And it is notable that in Python 3 you get an exception (error) if you try to use any
of the comparison operators, other than == and !=, to compare expressions that do not
have a natural comparison, like when comparing numbers with strings. A consequence of
this is that in Python 3 you cannot sort the elements of a list, according to value, where the
items have data types that are not comparable, because they cannot be ascribed as being
greater than or less than one another.
Python has two additional comparison operators:
x is y # rather than x == y
x is not y # rather than x != y
The difference between the two is that == and != compare the values while is and not is
compare whether objects are identical. Everything in Python is an object, and you might
be interested in whether two objects have the same value or are really the same object, a
stronger condition. As an analogy in the real world, two people might have the same name
but even if they have the same name it does not mean they are the same person. As an
example in Python:
x = [123, 54, 92, 87, 33] # x defined as a list
y = x[:] # y is a copy of x
y == x # True – same value
y is x # False – different object
Do'stlaringiz bilan baham: