Trying to understand how AND statement works inside abs(numbers) function.
Calling print(abs(21-22 and 9-4 and 11-8))
This would always give me whatever the last expression is. In this case it calculates 11-8, so it prints 3.
Why other expressions are not in the output and no error as well?
The fact that the expression is inside an abs call doesn't change the way that it's interpreted:
>>> 21-22 and 9-4 and 11-8
3
which is of course the same as:
>>> -1 and 5 and 3
3
An and evaluates the "truthiness" of each operand. If either of them is "falsey", that one is returned; otherwise the last one is returned.
All int values except 0 are "truthy", so the only time you'll get something other than the last value from an and of ints is if one of them is zero:
>>> -1 and 0 and 3
0
and is a logical operator, it will return True if both the operands of the operator are true. I believe the comma does what you expected to do in this case:
print(abs(21-22),abs(9-4),abs(11-8))
Related
I am studying the Python built-in method int(x), which casts a variable to int. The documentation is at https://docs.python.org/2/library/functions.html#int.
In a code I found:
errors += int(update != 0.0)
This code simply increases or decreases an error variable.
What i see is a conditional as a variable, even though the method doesn't take Boolean values. How is this possible?
Consider two possibilities:
int(True) and int(False)
First case will evaluate to 1 and second to 0
hence, errors will either increase by 1 or by 0
refer to the doc
Boolean values are the two constant objects False and True. They are used to represent truth values (although other values can also be considered false or true). In numeric contexts (for example when used as the argument to an arithmetic operator), they behave like the integers 0 and 1, respectively. The built-in function bool() can be used to convert any value to a Boolean, if the value can be interpreted as a truth value (see section Truth Value Testing above).
The Python 3 documentation is ever so slightly more straightforward than the 2 documentation here, so I’ll quote it:
Return an integer object constructed from a number or string x, or return 0 if no arguments are given. If x is a number, return x.__int__().
So int accepts a string or a number. Booleans aren’t strings, but they are in fact numbers! Following the link to Numeric Types – int, float, complex explains that…
There are three distinct numeric types: integers, floating point numbers, and complex numbers. In addition, Booleans are a subtype of integers.
which you can confirm in the REPL:
>>> import numbers
>>> isinstance(False, int)
True
>>> isinstance(True, numbers.Numeric)
True
and by doing math with booleans, which act as the integer values 0 and 1 as one would expect:
>>> True * 5
5
>>> math.acos(False)
1.5707963267948966
Booleans are a sub class of Integers in python and internally and False is represented as 0 in Python.
I recently encountered an example of an if-else conditional statement and could not understand the rationale behind its output. The following are the statements:
if 0:
1
else:
2
Output: 2
I tried different integers in 0's place, and received 1 each time. Is this because the zero in the if condition represents False? But then why do integers other than 1 still satisfy the if condition?
Thanks!
Edit: Thank you for all your answers. I now understand that any integer except 0 in the 'if' statement will make the statement True by default, resulting in an output of 1, in this case.
Python will always attempt to determine the "truthiness" of a given value used in a boolean context. In Python any numerical value of 0 (or 0.0) is considered false, and string, dictionary, list, or other iterable (or other class that can report its length) is false if it's empty or has length of 0. Also, None and boolean False are considered false.
Other values are considered true.
More details: https://docs.python.org/2.4/lib/truth.html.
In Python, bool is a subtype of int. False has the value 0, while other non-zero integers have the subtype bool with the value True.
To see this for yourself try this: False == 0
And to see the subtypes of int try this: int.__subclasses__()
1 is considered True while 0 is False,just like in binary.
Any non-zero numeric value is evaluated as True in a conditional statement.
bool type is just a subtype of int in Python, with 1 == True and 0 == False.
This question already has answers here:
Priority of the logical operators (order of operations) for NOT, AND, OR in Python
(8 answers)
Closed 6 years ago.
When I evaluate the following expression:
1 or (1/0) and 1
What are the rules (precedence, short-circuit evaluation etc) are followed to get the answer
b or anything_else is defined to return b if b is true-ish, without evaluating anything_else. Since your first 1 is true-ish, your 1/0 never gets evaluated, hence no error. By "true-ish" I mean any value that Python considers true, not only the True boolean value. Try your expression with True or [2] in place of the first 1 to see what I mean.
Python short-circuit evaluates. In your example, the expression
1 or (1/0) and 1
finishes evaluation at the first 1 and returns True.
A more minimal example serves to illustrate Python's short-circuit evaluation. Consider the expression:
(1/0) or 1
This raises a ZeroDivisionError exception upon evaluation of (1/0). But the expression:
1 or (1/0)
short-circuit evaluates to True. No exception is raised since the sub-expression (1/0) never gets evaluated.
This question already has answers here:
Does Python support short-circuiting?
(3 answers)
How do "and" and "or" act with non-boolean values?
(8 answers)
Closed 9 years ago.
When I test the difference between and and or, I meet this problem. Could you please help me understand it?
This behavior is a weird quirk that comes out of three different features of python code. Non-zeros values are true, logical operation evaluation, and short-circuiting. I'll explain these features below:
Non-Zero Values are True
The first thing you have to know in evaluating these expressions is that they are logical operators. They are designed to work with true or false values:
true and true = true
true and false = false
false and true = false
false and false = false
true or true = true
true or false = true
false or true = true
false or false = false
However, python (and many languages) allow you to put any value in. So long as they are non-zero they are considered true. So:
4 and 5 = true
4 and 0 = false
This is normal so far. Most languages have this.
Logical Operation Evaluation
Here Python does something a little unique. Instead of returning true or false, it actually returns the value of the last item it checked in the statement. So:
4 and 5 = 5 (which will be evaluated as true)
To fully understand which value will actually get returned you have to also understand:
Short-Circuiting
When evaluating these logical operators, the compiler can often stop early. Take the example:
3 or 4
We know that the statement will return true, but which value will it return? To figure this out you have to understand which value will be the last one looked at. The system will look at 3, and realize that the statement is true. It doesn't matter what the second value is, 3 or anything is true. So the value returned is 3 because it is the last value checked.
However, if we use and:
3 and 4
Once we look at 3, we still need to check that the second value is true. It could makes a difference. So the second value is evaluated. If it is true, it returns the last value looked at, in this case 4.
In Conclusion
You just have to think about which value the interpreter can stop on.
3 or 4 = 3 // because we can stop at 3
3 and 4 = 4 // because we have to check the 4
0 or 3 = 3 // because we needed to check the 3
Yes, the and operator requires all arguments to be true, and returns the last one checked, which is 5. (If any of the arguments were false, it would return the first false value, since that would be the last one checked in order to verify if all arguments were true.)
The or operator requires only one argument to be true, and returns the last one checked, which is 4, because 4 represents the first true value in the conditional. (If all arguments were false, then the return value would be equal to the last false value, since that would be the last value checked in order to verify if any of the arguments were true.)
true1 and true2 >>>true2
true1 or true2 >>>true1
when runinng true1 and true2, python must check the value returned by every expression is true or not, so it will return the last one.
but when running true1 or true2 , as true1 retrun "true" (in your example, 4 is "true") already, so it is unncessary to continue checking the rest.
I think the way to look at it is at a simpler level, which was designed for optimization.
and requires that both sides be "truthy." It checks the left side. If it is "truthy," it returns the second value without checking what it is.
or requires only one side to be "truthy." It checks the first side. If it is "truthy," it returns it. If not, it returns the second side, again without checking it.
For "4 and 5", because 4 is "truthy," it returns 5.
For "4 or 5", it returns 4 without even looking at 5.
Need proof? Make these functions:
def four():
print 'Evaluating four!'
return 4
def five():
print 'Evaluating five!'
return 5
Now see what gets printed:
>>> four() and five()
Evaluating four!
Evaluating five!
5
and evaluated four(), and since it was true it returned five().
>>> left() or right()
Evaluating left side!
4
or evaluated four() and since it was true, returned four() without even calling five()!
This question already has answers here:
How do "and" and "or" act with non-boolean values?
(8 answers)
Closed 6 months ago.
I'm a little confused with the results I'm getting with the logical operators in Python. I'm a beginner and studying with the use of a few books, but they don't explain in as much detail as I'd like.
here is my own code:
five = 5
two = 2
print five and two
>> 2
It seems to be just outputting the two variable.
five = 5
two = 2
zero = 0
print five and two and zero
So, I added another variable integer. Then I printed and got the following output:
>> 0
What is going on with Python in the background? Why isn't the output something like 7 or 5, 2.
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 evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.
As a bit of a side note: (i don't have enough rep for a comment) The AND operator is not needed for printing multiple variables. You can simply separate variable names with commas such as print five, two instead of print five AND two. You can also use escapes to add variables to a print line such as print "the var five is equal to: %s" %five. More on that here: http://docs.python.org/2/library/re.html#simulating-scanf
Like others have said AND is a logical operator and used to string together multiple conditions, such as
if (five == 5) AND (two == 2):
print five, two
Boolean And operators will return the first value 5 if the expression evaluated is false, and the second value 2 if the expression evaluated is true. Because 5 and 2 are both real, non-false, and non-null values, the expression is evaluated to true.
If you wanted to print both variables you could concatenate them to a String and print that.
five = 5
two = 2
print five + " and " + two
Or to print their sum you could use
print five + two
This document explains how to use the logical Boolean operators.
This AND in Python is an equivalent of the && in Java for instance. This doesn't mean the and in the English language. The AND is a logical operator. Assume five holds 5 and two holds 2. From Python documentation: 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. Basically, it evaluates the last integer in your case which is true.
if (five and two):
... print "True"
... else:
... print "False"
The AND is a logical operator, to test the logic for a specific case, not an arithmetic operator. If you want to get results like 7 for five and two, you should rather use "+" which means adding two integers. See below:
>>> five = 5
>>> two = 2
>>> print five + two
7
Try 0 and 9.
The result is 0 because the value of 0 is false. The operand on the left of the and operator is False so the whole expression is False and returns 0
In Python any non-zero integer value is true; zero is false.
The OP’s values are both non-zero.
The AND operator tests from left to right,
with and, if all values are True, returns the last evaluated value.
If any value is false, returns the first one.
Since both are non-zero, both are true, so the last value is returned
To convert the integer variable to a string , add str in front of each variable
five = 5
two = 2
print(str(five) + " and " + str(two))