There are three logical operators that we can use and
these logical operators are: and, or and not. The semantics of these operators
is similar to their meaning in English language. For example:
>>>x=5 >>>x>0 and x < 10 True
The previous expression is True because x is 5 and is
greater than 0 and less than 10. So using logical operator and the result will
be true only if two of the expressions are true otherwise will be false.
>>>n=6 >>>n % 2 == 0 or n%3 == 0 True
The expression is true if either of the conditions is
true, that is, if the number is divisible by 2 or 3.
Finally, the not operator negates a boolean
expression, so not (x > y) is true if x > y is false, that is, if x is
less than or equal to y.
Strictly speaking, the operands of the logical
operators should be boolean expressions, but Python is not very strict. Any
nonzero number is interpreted as “true.”
>>> 17 and True True
This flexibility can be useful, but there are some
subtleties to it that might be confusing. You might want to avoid it (unless
you know what you are doing).
Nema komentara:
Objavi komentar