logical operators 'or' and 'and' in variable python
and
and or
are operators, like +
and -
, and cannot be assigned to variables. Unlike +
et al., there are no functions that implement them, due to short-circuting: a and b
only evaluates b
if a
has a truthy value, while foo(a, b)
must evaluate both a
and b
before foo
is called.
The closest equivalent would be the any
and all
functions, each of which returns true as soon as it finds a true or false value, respectively, in its argument.
>>> any([1+2==3, 3+1==5]) # Only needs the first element of the list
True
>>> all([3+1==5, 1+2==3]) # Only needs the first element of the list
False
Since these are ordinary functions, you can bind them to a variable.
if True:
logical_obj = any
else:
logical_obj = all
if logical_obj([1 + 2 == 3, 3 + 1 == 5]):
pass
The list has to be fully evaluated before the function can be called, but if the iterable is lazily generated, you can prevent expressions from being evaluated until necessary:
>>> def values():
... yield 1 + 2 == 3
... print("Not reached by any()")
... yield 3 + 1 == 5
... print("Not reached by all()")
...
>>> any(values())
True
>>> all(values())
Not reached by any()
False
Python's Logical Operator AND
Python Boolean operators return the last value evaluated, not True/False. The docs have a good explanation of this:
The expression
x and y
first evaluatesx
; ifx
isfalse
, its value is returned; otherwise,y
is evaluated and the resulting value is returned.
Logical operators for Boolean indexing in Pandas
When you say
(a['x']==1) and (a['y']==10)
You are implicitly asking Python to convert (a['x']==1)
and (a['y']==10)
to Boolean values.
NumPy arrays (of length greater than 1) and Pandas objects such as Series do not have a Boolean value -- in other words, they raise
ValueError: The truth value of an array is ambiguous. Use a.empty, a.any() or a.all().
when used as a Boolean value. That's because it's unclear when it should be True or False. Some users might assume they are True if they have non-zero length, like a Python list. Others might desire for it to be True only if all its elements are True. Others might want it to be True if any of its elements are True.
Because there are so many conflicting expectations, the designers of NumPy and Pandas refuse to guess, and instead raise a ValueError.
Instead, you must be explicit, by calling the empty()
, all()
or any()
method to indicate which behavior you desire.
In this case, however, it looks like you do not want Boolean evaluation, you want element-wise logical-and. That is what the &
binary operator performs:
(a['x']==1) & (a['y']==10)
returns a boolean array.
By the way, as alexpmil notes,
the parentheses are mandatory since &
has a higher operator precedence than ==
.
Without the parentheses, a['x']==1 & a['y']==10
would be evaluated as a['x'] == (1 & a['y']) == 10
which would in turn be equivalent to the chained comparison (a['x'] == (1 & a['y'])) and ((1 & a['y']) == 10)
. That is an expression of the form Series and Series
.
The use of and
with two Series would again trigger the same ValueError
as above. That's why the parentheses are mandatory.
How does the logical `and` operator work with integers?
From the Python documentation:
The expression
x and y
first evaluatesx
; ifx
is false, its
value is returned; otherwise,y
is evaluated and the resulting value
is returned.
Which is exactly what your experiment shows happening. All of your x
values are true, so the y
value is returned.
https://docs.python.org/3/reference/expressions.html#and
Using logical operators in an expression
x and y
is x
if it is "false-y" (i.e. 0
, False
, None
, []
, ''
, ...), otherwise it is y
.x or y
is x
if it is "truth-y", otherwise it is y
.
That is, x or y
is the same as x if x else y
, and x and y
the same as x if not x else y
.
Advance Logical Operator in Python
If you are thinking of trying to emulate JavaScript or other languages ternary operators, you have to do it something like this:
print("even" if a%2 == 0 else "odd")
edit: even though this question has been closed (and I don't believe it should be) I will edit it with the understanding about what your question is actually asking.
In python bool(1) == True
and bool(0) == False
notice how when you modulo 2 these are the only two possible values you can get.
Now go back to your origional print statement:
print(a%2 and 'odd' or 'even')
Combine the fact that 1 is true and 0 is false with the fact that the first condition of a statement ... and [...] or ...
returns if the statement is true and the second returns if it is false.
It is then clear to see that when the number is odd causing the number modulo 2 to be 1 it will return the first condition "odd" and when it is 0 it will cause the second condition to be returned "even".
I hope this explains everything.
Define the order of terms in and logical operator
The and
operator already evaluates arguments left-to-right. It's also a short-circuit operator i.e. it only evaluates the right argument if the left one is true (since if it was false then the expression would return false whatever the right argument is)
Related Topics
Flask to Return Image Stored in Database
How to Make File Creation an Atomic Operation
How to Put Multiple Statements in One Line
Complexity of *In* Operator in Python
Calculate Average of Every X Rows in a Table and Create New Table
How to Convert Columns into One Datetime Column in Pandas
Calculate Area of Polygon Given (X,Y) Coordinates
"Sys.Getsizeof(Int)" Returns an Unreasonably Large Value
Defining a Discrete Colormap for Imshow in Matplotlib
What Happens When a Module Is Imported Twice
Add Pygame Module in Pycharm Ide
Python JSON Parser Allow Duplicate Keys
What Do the Python File Extensions, .Pyc .Pyd .Pyo Stand For