And/Or Operators Return Value

and / or operators return value

The and and or operators do return one of their operands, not a pure boolean value like True or False:

>>> 0 or 42
42
>>> 0 and 42
0

Whereas not always returns a pure boolean value:

>>> not 0
True
>>> not 42
False

Why do 'and' & 'or' return operands in Python?

I think you're somehow confused about what the docs says. Take a look at these two docs sections: Truth Value Testing and Boolean Operators. To quote the last paragraph on the fist section:

Operations and built-in functions that have a Boolean result always return 0 or False for false and 1 or True for true, unless otherwise stated. (Important exception: the Boolean operations or and and always return one of their operands.)

As you can see, you're right about operations and built-in functions but see the Important exception part, it is well stated that the Boolean operators will return one of their operands.

Now, what they can return depends hardly on the operator's short circuit logic. For or operator, it will return the first truthy value in the expression, since when it finds one, the whole expression is true. In case of every operand being falsey, or will return the last operand, meaning that it iterated over every one of them not being able to find a truthy one.

For and operator, if the expression is true, it will return the last operand, if the expression is false, it will return the first falsey operand. You can read more about Short Circuit Evaluation at the Wikipedia Page.

You have a lot of examples in your question, let's analyze some of them:

>>> False and 1  # return false (short circuited at first falsey value)
False
>>> True and 1 # return 1 (never short circuited and return the last truthy value)
1
>>> 1 and False # return false (short circuited at first falsey value, in this case the last operand)
False
>>> 1 and True # return True (never short circuited and return the last truthy value)
True
>>> True and 121 # return 121 (never short circuited and return the last truthy value)
121
>>> False or 1 # return 1 (since the first operand was falsey, or kept looking for a first truthy value which happened to be the last operator)
1
>>> False or 112 # return 112 for same reason as above
112
>>> False or "Khadijah" # return "Khadijah" for same reason as above
'Khadijah'
>>> True and 'Khadijah' # return "Khadijah" because same reason as second example
'Khadijah'

I think this should make a point. To help you further understand why this is useful, consider the following example:

You have a function that randomly generate names

import random

def generate_name():
return random.choice(['John', 'Carl', 'Tiffany'])

and you have a variable that you don't know if it has assigned a name yet so instead of doing:

if var is None:
var = generate_name()

You can do oneliner:

var = var or generate_name()

Since None is a falsey value, or will continue its search and evaluate second operand, this is, call the function ultimately returning the generated name. This is a very silly example, I have seen better usages (although not in Python) of this kind of style. I couldn't come out with a better example right now. You can also take a look at this questions, there are very useful answers on the topic: Does Python support short-circuiting?

Last but not least, this has nothing to do with static typed, duck typed, dynamic, interpreted, compiled, whatever language. It's just a language feature, one that might come handy and that is very common since almost every programming language I can think of provide this feature.

Hope this helps!

Why is and operator on two values gives the last value?

Logical operators operate on the truthiness of an object. Every object has truth value, unless it has a __bool__ method that is explicitly overridden to raise an error. The major difference between a and b (logical) and a & b (bitwise) is that the former apply to any objects, while the latter only apply to numeric types that support bitwise operations.

Python's logical operators are specifically designed to return the result of the last object evaluated:

  • a and b: Returns a Falsy a, or b (if a is truthy)
  • a or b: Returns a Truthy a, or b (if a if falsy)

From the tutorial:

The Boolean operators and and or are so-called short-circuit operators: their arguments are evaluated from left to right, and evaluation stops as soon as the outcome is determined. For example, if A and C are true but B is false, A and B and C does not evaluate the expression C. When used as a general value and not as a Boolean, the return value of a short-circuit operator is the last evaluated argument.

This property is used semi-idiomatically to check values before accessing them. For example, if a list must contain an element, you can do something like

if x and x[0] == value:
# ...

This will not raise an error, because if x is Falsy (empty), the and expression will return x instead of x[0] == value.

How do and and or act with non-boolean values?

TL;DR

We start by summarising the two behaviour of the two logical operators and and or. These idioms will form the basis of our discussion below.

and

Return the first Falsy value if there are any, else return the last
value in the expression.

or

Return the first Truthy value if there are any, else return the last
value in the expression.

The behaviour is also summarised in the docs, especially in this table:























OperationResult
x or yif x is false, then y, else x
x and yif x is false, then x, else y
not xif x is false, then True, else False

An or operator in a return?

The line return (m(s1 + 1, s2) || m(s1 + 1, s2 + 1)); can be rewritten in this form:

if ( m(s1 + 1, s2) )
{
/* if left part not null, return 1, without
evaluationg the right part */
return 1;
}
else if ( m(s1 + 1, s2 + 1) )
{
/* if left was 0, test right part */
return 1;
}
else
{
/* if both are null, return 0*/
return 0;
}

Javascript Logical OR operator in return statement of a function

(title) => !!title || "Title is required"]

This line is saying:
If title is present, return true, otherwise return "Title is required".

Let's break it down...


To start with, the arrow function is just shorthand for:

function xxxx (title) {
return !!title || "Title is required"];
}

Next, the !! is a double negation, effectively just the logical not opperator twice. The first negation converts the data (whatever it data type it may be) to a boolean. The second negation changes the boolean again to give the desired result.

E.g. !!'hello' --> true, !!0 --> false, !!undefined --> false


The next part is a comparison. The || is OR opperator, so if the first half is true / present, then it will be returned, if not, the part after the || will be returned.

E.g. true || 'some text' will return true, wheras false || 'some text' will return some text


Here are some example, try running the snippet to see the outputs

const checkTitle = (title) => !!title || "Title is required"

// 1. No parameters, should print "Title is required"
console.log('Test 1', checkTitle());

// 2. Parameter presentbut empty, should print "Title is required"
console.log('Test 2', checkTitle(""));

// 3. Title present, and valid, should preint 'true'
console.log('Test 3', checkTitle('Hello World!'));

Return value with logic operators

should be the same

int consecutive_3(int x, int y, int z, int a[], int n)
{
if (n < 3)
return 0;

if ((a[n-3] == x) && (a[n-2] == y) && (a[n-1] == z))
return 1;

return consecutive_3(x, y, z, a, n - 1);
}

notice: c evaluates logical expressions from left to right and && has a higher precedence (is evaluatet first) than ||.

returning the higher value in logical operators in javascript

From MDN on the && operator:

"If expr1 can be converted to true, returns expr2; else, returns
expr1."

So in this case, 1 can be converted to true, so it returns the second value, 5.

How does and&or work in print() function?

This is an old style way to use ternary condition operator.

It has nothing related to print.

See this answer.

In most cases it does the same as this code

print(T and sorted(sorted(T,reverse=True),key=abs)[0] or 0)
print(sorted(sorted(T,reverse=True),key=abs)[0] if T else 0)

It works because of the way and and or works in Python - they do not return bool, but they return either first or second operand, depending if it casts to True or False.

This answer has more details.

Basically it's two operation

first = T and sorted(sorted(T,reverse=True),key=abs)[0]

and Return the first Falsy value if there are any, else return the last value in the expression.

So it either returns [] (possible Falsy value for T), or first element in sorted list.

result = first or 0

or Return the first Truthy value if there are any, else return the last value in the expression.

So if T is Truthy, we already have a Truthy value in first (unless it's 0, which is special case, but 0 or 0 is 0 anyway), it will be returned.

If T is [] - it will return 0.

Python: justification for boolean operators (and, or) not returning booleans

In Python's case, the bool type didn't even exist until over a decade after the language was released. If it had existed from the start, perhaps and and or would have been defined differently. But, as is, backward compatibility was far more important. From the PEP that introduced the type:

Another consequence of the compatibility requirement is that the expression "True and 6" has the value 6, and similarly the expression "False or None" has the value None. The "and" and "or" operators are usefully defined to return the first argument that determines the outcome, and this won't change; in particular, they don't force the outcome to be a bool. Of course, if both arguments are bools, the outcome is always a bool. It can also easily be coerced into being a bool by writing for example "bool(x and y)".

EDIT: BTW, at its start, Python was intended to "bridge the gap" between programming in "data-rich" languages like C and "convenient" languages like Unixy shells (sh, csh, etc). Python's and and or were more like && and || act in shell languages, consuming - left to right - all and only the operands needed to resolve whether the overall chain succeeded ("true") or failed ("false").



Related Topics



Leave a reply



Submit