I found a snippet in our code base that looks kind of useless to me but I suspect that somebody put it there for a reason that eludes me; so I thought I'd ask around. The part is something like this:
someParam = 'nope' # someParam is actually a query result, not a fixed string
if someParam != 'nope' and True or False
In my opinion the and True or False is doing exactly nothing for the evaluation and can be removed since the first part, the equality check, combined with the and True (operator precedence and > or, IIRC) is the same as the first part:
If first part evaluates to True -> True and True -> True
If the first part is False -> False and True -> False
now those results with the appended or False:
True or False -> True
False or False -> False
So the result of the condition would not change if I removed the and True or False, correct? Or am I missing something here?
Also could the behaviour of this change while switching from Python 2 to 3? I think not but I'm not quite sure.
You can remove and True or False from if statement, as it return same result what someParam != 'nope' will give.
You can check it by simple example as:
True and True or False
The output is always True Whereas
False and True or False
The output is always False
As you say, the expression foo and True or False is just a complicated way of converting the "truthiness" of the value foo into an actual boolean:
>>> 'foo' and True or False # non-empty strings are truth-y
True
>>> '' and True or False # empty strings are false-y
False
(You can see the rules for built-in types' truthiness here.)
This is because and and or return one of their operands, per the docs:
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.
and, as you say, the operator precedence for and is higher than or.
That code is totally redundant, for a number of reasons:
Because Python already gives you a built-in way to do that, bool:
>>> bool('foo')
True
>>> bool('')
False
Because foo is already a boolean anyway; != is a comparison, and the result of any comparison is either True or False, so any conversion to boolean is redundant.
Because in a context like if foo:, even if foo wasn't already boolean, Python will automatically evaluate the truthiness of foo rather than only accepting a boolean, so if foo and True or False: and if bool(foo) are both pointless; you can just write if foo:.
And no, none of the above points changed between Python 2 and 3. You can check the equivalent links for all of the above in the new version:
Truthiness
Boolean operations
Operator precedence
bool
Comparisons
Yes, x and True or False can be simplified to just x when x is a boolean value.
Related
It says in python 2.7 docs that or has lower precedence than and. But when I type in idle this:
>>> True and True or False
True
>>> True and False or True
True
>>> True and False
False
Why is the result of this True and False or True expression True?
Higher precedence means that an operator would be evaluated before an operator with lower precedence, like, e.g., in arithmetic, multiplication should evaluated before addition, so 1 + 2 * 3 will result in 7 and not 9.
In your usecase, True and False is evaluated first, giving False. This result is then evaluated with the or operator (i.e., False or True), resulting in True.
In fact, operator precedence has nothing to do with this result; it would be the same wherever you put the parentheses, since or always returns True if either of its arguments are true. So:
True and (False or True) == True and (True) == True
(True and False) or True == (False) or True == True
You statement is asking to do the following
First python evaluates the expression on the left;
Evaluation 1: True and false (Since this evaluates to false python then looks to the or expression)
Evaluation 2: True or false
Which then evaluates to true
You may also want to take a look at Boolean logic and truth tables to assist with understanding how this works.
Highest precedence means where you will put the parentheses
((True and True) or False) # True
((True and False) or True) # True
(True and False) # False
I cant seem to grasp Bootlean operators. I'm using an example from Code Academy. At first I read it wrong and was putting True or not False and False Instead of True or False.
Can someone explain this a bit more clearly for me so I can get more of an understanding.
Assign True or False as appropriate for bool_one through bool_five.
Set bool_one equal to the result of False or not True and True
Set bool_two equal to the result of False and not True or True
Set bool_three equal to the result of True and not (False or False)
Set bool_four equal to the result of not not True or False and not True
Set bool_five equal to the result of False or not (True and True)
You have three boolean operations and some rules:
not, which just inverses (aka not True => False, not False => True)
or, which works on two operands x or y and returns True if either is True and False if they are both False
and, which works on two operands x and y and returns True if both are True and False otherwise
They are evaluated from left to right
not has the highest precedence, and after that, lastly or
You can use () to change the precedence of operations, just as in everyday math
5.15 Operator Precendence (listed lowest to highest, and I trimmed many operators)
or
and
not
(expressions...)
So you can see that from low to high precedence it is or then and then not then (). Example
False or not True and True
So if I add parentheses to emphasize order
(False or (not True)) and (True)
becomes
(False or False) and (True)
False and True
False
You can follow this process with the other lines
A boolean variable can have one of two values - True or False. There are several operators that can help you manipulate boolean values:
not inverts the value - True becomes False and vise-versa
and returns True if and only if both operands evaluate to True
or returns True if either or the operands evaluate to True
This exercise asks you to translate the English statements to python:
bool_one = False or not True and True
bool_two = False and not True or True
bool_three = True and not (False or False)
bool_four = not not True or False and not True
bool_five = False or not (True and True)
I am reading about booleans in my book, and it says:
x and y------------If x is false, return x. Otherwise, return y.
x or y--------------If x is true, return x. Otherwise, return y.
This doesn't make sense to me from the everyday usage of "or" and "and"
To me, it would make sense if it said:
x and y------------If x is false, do nothing. If y is false, do nothing. If x and y are true, return x and y
x or y--------------If x is true, return x. If x is false, check y. If y is false, do nothing. If y is true, return y
Do I just need to blindly accept the actual definitions, or can I understand them because they actually make sense.
"Do nothing" isn't an option. The mathematical expression x or y must have a value (which is true if either x, y, or both is true). And x and y must have a value (which is true if and only if x and y are both true).
The way your book defines them is mathematically correct, but confusing (until you get into things like short-circuit evaluation).
The behavior may seem strange, but consider the following hypothetical examples. Starting with something obvious,
>>> True and False
False
>>> False and True
False
this is really easy to understand since we're dealing with boolean values. Remember this example, because every other example can be thought of this way.
Now consider if the and and or operators were to convert every object to a boolean before comparing. For example, an empty string or empty list would be False, and non-empty ones would be True. It would look like this (obviously this is not what it ACTUALLY looks like)
>>> "vanilla" and ""
False
>>> "" and "vanilla"
False
This makes perfect sense. After all bool("vanilla") and bool("") would be the same as True and False which we already know is False
Instead of actually converting them to True or False, though, it can do the comparison without ever converting them. As a result, you don't really need it to return True or False. It can just return the actual object it tested.
>>> "vanilla" and ""
""
>>> "" and "vanilla"
""
For truth testing purposes, returning "" is the same as returning False, so there's no need to convert it to a boolean. That's why it always returns an object whose truth value is the same as the result of the operator.
Unlike some other languages, you can use any object as operands of boolean operations. All your books says is that you can use boolean operators as a quick "filter" of values.
For instance, say you want to choose a non-empty list between two lists. The following is a valid (and more Pythonic) way to do it:
>>> [] or ['something', 'here']
['something', 'here']
Contrast to (not making use of Python idioms in Python):
if len(l1) != 0:
return l1
else:
return l2
Your book is right - see the documentation. It might be unintuitive at first, but this behavior (called short-circuiting) is extremely useful. In a simple case, it allows you to save a lot of time when checking certain conditions. In this example, where function f takes 10 seconds to evaluate, you can definitely see one use:
if f(foo) or f(bar) or f(baz):
If f(foo) is True, then there is no need to evaluate f(bar) or f(baz), as the whole if statement will be True. Those values are unnecessary and you'll just be wasting your time computing them.
Another extremely common use of this behavior is in null (or for python None) checking. It allows safe usage of functions all within one line:
if obj != None and obj.foo():
If obj is None, the if statement is guaranteed to be False, and so there is no need to check (or even evaluate) obj.foo(), which is good, since that would cause an exception.
Short-circuiting is very common in many programming languages, and is very useful once you fully understand how to use it.
While the book presents it in a slightly confusing way, it is correct. Boolean logic must evaluate to either true or false.
For X and Y in order to return true they both must be true, if X is false then it returns false. If X is true then it returns Y which is either true or false and also the correct answer.
For X or Y to return false they both must be false. If X is true then it can return true (X). If X is false then it returns whatever the value of Y is.
Many (most?) programming languages, including Python, implement short-circuiting in their boolean operators and and or. So they evaluate their operands from left to right, and stop as soon as the final result can be determined.
Since x and y and z and ... is guaranteed be false if any operand is false, it stops evaluating the operands as soon as it encounters a false one. And x or y or z or ... is guaranteed to be true if any operand is true, so it stops as soon as it reaches a true operand. In either case, if they make it all the way to the last operand, they return its value.
In some languages, the boolean operators just return a strict boolean result, either true or false (in some languages these are represented as 1 and 0). But in Python (and some others, such as Javascript and Common Lisp), they return the value of the last operand that was evaluated, which determined the final result. This is often more useful than just the truth value of the expression.
When you put these features together, it allows some succinct idioms, e.g.
quotient = b != 0 && a/b
instead of
if b != 0:
quotient = false
else:
quotient = a/b
The first set of descriptions are shortcuts: following these will give you exactly the same results as the "usual definitions" of true and false.
But your own descriptions don't make much sense. You can't "do nothing"; you have to return some value from a comparison, either true or false. And you can't return both a and b, either: again, the result of a boolean comparison must be a boolean, not a pair of booleans.
Its probably easier if you think about it in each literal case
x and y------------If x is false, return x. Otherwise, return y.
x or y--------------If x is true, return x. Otherwise, return y.
CASE 1: x = true, y = true
"if x is false, return x. Otherwise, return y."
Then this will return y which is true. This makes sense because x and y are both true.
(true and true == true)
"If x is true, return x. Otherwise, return y."
The this will return x which is true. This makes sense because one of x or y is true.
(true or true == true)
CASE 2: x = false, y = true
"if x is false, return x. Otherwise, return y."
Then this will return x which is false. This makes sense because x and y are not both true.
(false and true == false)
"If x is true, return x. Otherwise, return y."
The this will return y. This makes sense because one of x or y is true.
(false or true == true)
CASE 3: x = true, y = false
"if x is false, return x. Otherwise, return y."
Then this will return y which is false. This makes sense because x and y are not both true.
(true and false == false)
"If x is true, return x. Otherwise, return y."
Then this will return x which is true. This makes sense because x or y is true
(true or false == true)
CASE 4: x = false, y = false
"if x is false, return x. Otherwise, return y."
Then this will return x which is false. This makes sense because x and y are not both true.
(false and false == false)
"If x is true, return x. Otherwise, return y."
The this will return y which is false. This makes sense because neither x nor y is true.
(false or false == false)
I have this code in a boolean context:
True and False or 2
Output: 2
The type check for this expression resulted in int.
Next, I modified the code to:
True and False or True
Output : True
And the type check for this expression resulted in bool
Why is the output in the 1st code 2?
Shouldn't the expression evaluate to a boolean value ?
If not so, Why?
All you need to know here is the definition of OR operand.Based on python documentation :
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.
So since the precedence of or is lower than and your expression evaluated as following :
(True and False) or 2
Which is equal to following :
False or 2
Thus based on preceding documentation the result would be the value of right object which is 2.
In Python, when using 'and' and 'or', the expression evaluates using the objects involved, instead of using Booleans as in many other languages.
So:
1 and 2 will evaluate to 2
1 or 2 will evaluate to 1 (short-circuit)
1 and "hello" will evaluate to "hello"
... and so on
If you want the Boolean, just surround the whole expression with bool(..)
Further reading:
http://www.diveintopython.net/power_of_introspection/and_or.html
https://docs.python.org/2/reference/expressions.html#boolean-operations
When you said True and False it is evaluate to False.
Then you have False or 2 which will evaluate to 2
Now True and False or True will evaluate to True but the last True in your expression. This is due to operator precedence
>>> True and False
False
>>> False or 2
2
>>>
The output is 2 not True because True and False or 2 is like
var = (True and False)
if var:
print(var)
else:
print(2)
which yields
2
because True and False will always evaluate to False
I think you are clear with the operator precedence between and and or.According to Python documentation, the object is returned.
>>> 1 and 2
will return 2 according to the shorcut evaluation.
and so on.
Apologies if this has been asked before, but I have searched in vain for an answer to my exact question. Basically, with Python 2.7, I have a program running a series of geoprocessing tools, depended on what is reqested via a series of True/False variables that the user adjusts in the script e.g.
x = True
if x:
run function
However, I have now discovered that x does not need to be literally "True" for the function to run. For example:
In: x = True
if x:
print True
Out: True
In: x = 123
if x:
print True
Out: True
In: x = 'False'
if x:
print True
Out: True
In: x = False
if x:
print True
Out:
So any value other than False appears to evaluate to True, which would not be the case for if x == True or if x is True. Seeing as PEP 8 strongly recommends only using the if x: variant, can anybody explain why this behaviour occurs? It seems that if x: is more a test for "if x is not False" or "if x exists". With that in mind, I believe I should be using if x is True: in this case, despite what PEP 8 has to say.
The following values in Python are false in the context of if and other logical contexts:
False
None
numeric values equal to 0, such as 0, 0.0, -0.0
empty strings: '' and u''
empty containers (such as lists, tuples and dictionaries)
anything that implements __bool__ (in Python3) to return False, or __nonzero__ (in Python2) to return False or 0.
anything that doesn't implement __bool__ (in Python3) or __nonzero__ (in Python2), but does implement __len__ to return a value equal to 0
An object is considered "false" if any of those applies, and "true" otherwise, regardless of whether it's actually equal to or identical with False or True
Now, if you've arranged that x is necessarily one of the objects True or False, then you can safely write if x. If you've arranged that the "trueness" of x indicates whether or not to perform the operation, regardless of type, then you can safely write if x. Where you can write that you should prefer to do so, since it's cleaner to read.
Normally, if it is allowed for x to take the value True then you're in one of those two cases, and so you would not write if x is True. The important thing is to correctly document the meaning of x, so that it reflects the test used in the code.
Python programmers are expected to know what's considered true, so if you just document, "runs the function if x is true", then that expresses what your original code does. Documenting it, "runs the function if x is True" would have a different meaning, and is less commonly used precisely because of the style rule in PEP8 that says to test for trueness rather than the specific value True.
However, if you wanted the code to behave differently in the case where x is an empty container from the case where it is None, then you would write something like if x is not None.
I'd like to add a short example where those 3 tests differ:
def test(x):
print(x, ":", bool(x), x == True, x is True)
test("something")
test(1)
test(True)
The output (pretty formatted):
# "something" : True False False
# 1 : True True False
# True : True True True
x = 'False'
x = 123
Are both True
Other truth values.
The document explains other values.
As far as the PEP8 reason, its far more semantic to read if this_file_is_green
Other falsey values include 0, '', []. You should just use the if x: version.
It goes without saying that you should write code that does what you need. But in most cases, you simply don't need to say == True or is True, because you don't need to distinguish True from other "truthy" values. So it's recommended to leave that out for simplicity.
The case where you definitely should use == True or is True is when you do need to distinguish True from other truthy values.
In your example, do you care about the difference between True and 123? That would tell you which way to code it.
One thing about coding == True or is True: it will raise a minor red flag when other developers read your code. They won't think it's wrong, they will just wonder why it's there and will want to know why it's important to treat True differently from other truthy values in this particular case.
In other words, if you don't need it, it's best not to use it.
The ability to say
if x:
...
is considered a feature. You can also specify when the test should be considered to pass or not for user defined classes (just define the method __nonzero__ in Python 2.x or __bool__ in Python 3).
For example for strings and containers like lists, dictionaries or sets the test if x ... means "if x is not empty".
Note that the rationale is not that this allows less code to write, but that resulting code is easier to read and to understand.
If you like instead to write if x is True ... have you considered to go farther down that path to if (x is True) is True ... or if ((x is True) is True) is True ... ? :-)
In Python 2.7, if a: and if a==True are not giving the same output for values different to 1. Here are some snippets of code to demonstrate the different behaviors:
with a=1
a=1
if a==True:
print (a,"True")
else:
print (a,"Not True")
output> (1,True)
a=1
if a:
print (a,"True")
else:
print (a,"Not True")
output> (1, True)
with a=2
a=2
if a:
print (a,"True")
else:
print (a,"Not True")
output> (2, True)
a=2
if a==True:
print (a,"True")
else:
print (a,"Not True")
output> (2, Not True)
if you use if x ,it means it has to evaluate x for its truth value.But when you use x ==True or x is True.It means checking whether type(x)==bool and whether x is True.
attention : x is True is no equal to bool(x)==True
when you use x is True , you are checking the id of x and True.