Python Forum

Full Version: Python logical operator AND
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
#Python Code
a = 6
b = 7
print (a and b)
#End code

Why the result of the print function is 7 instead of 6?

If:
0110 ->6
AND 0111 ->7
-------
0110 ->6

Thanks!
from the docs:
Quote:The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.

also here:
Quote:Boolean Operations — and, or, not

These are the Boolean operations, ordered by ascending priority:
  • x or y: if x is false, then y, else x (1)
  • x and y: if x is false, then x, else y (2)
  • not x: if x is false, then True, else False (3)

Notes:
  1. This is a short-circuit operator, so it only evaluates the second argument if the first one is false.
  2. This is a short-circuit operator, so it only evaluates the second argument if the first one is true.
  3. not has a lower priority than non-Boolean operators, so not a == b is interpreted as not (a == b), and a == not b is a syntax error.
According to the python Docs :-
In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: False, None, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true. User-defined objects can customize their truth value by providing a __bool__() method.

The operator not yields True if its argument is false, False otherwise.

The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.

The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.

Note that neither and nor or restrict the value and type they return to False and True, but rather return the last evaluated argument. This is sometimes useful, e.g., if s is a string that should be replaced by a default value if it is empty, the expression s or 'foo' yields the desired value. Because not has to create a new value, it returns a boolean value regardless of the type of its argument (for example, not 'foo' produces False rather than ''.)
To get the result that you are expecting, you would use bitwise operators.
a = 6
b = 7
print(a & b) #& is bitwise and
As a matter of fact, using or will give the same result, but I don't think it will be preferred to do so. @TomToad indeed gave the correct and right solution