# x = 1
# x = 0
if x:
print(f'x = {x}, and therefore it\'s truthy')
else:
print(f"x = {x}, and therefore it's falsey")
Hi everyone, I am a little confused with this exercise. The code doesn't have any explanation as when the system should print truthy or falsey yet it knows when to print it. Why is that?
I think it's just a way to show that 0 is interpreted as False in a boolean expression like a comparison or an if etc, and 1 (or any other non-zero number) is interpreted as True.
Edit: and like said in some comments, the fact that a value is "truthy" doesn't mean that is strictly equal to True
for example:
print(1 == True) # True
print(0 == False) # True
print(2 == True) # False
print(not not 2) # True
print(not 0) # True
print(not not 0) # False
print(0 and True) # False
print(2 and False) # False
print(2 and True) # True
print(0 or 2) # True
# etc ...
If x is an int and has a value of zero it is equal to False and therefore falsey. If x is an int and has a value of 1 it is equal to True and is therefore truthy. However, if x is an int and is neither 0 nor 1 it is truthy but not equal to True. Therefore, when x is of type int, if x: can be interpreted as 'if x is non-zero'
Its all in the if x: line.
To execute this line, I like to think that python translates it to:
if bool(x):
because bool() will only ever return True or False, then the first option is only ever taken when the result is True.
See this answer for details of a comprehensive list of values which are considered Falsey.
the funny part is if you use
x = 0.00000000000001
it will also consider as true. cause it is not actually equal to zero. in math we consider this as zero for easy calculation. but computer dont do this cause this can create big problem in calculation if we consider a big picture. Example:
y = x ** x
print(y)
so if we consider x as zero, y will be also zero. but its not.
i hope you enjoyed to learn why 0.000000000001 is not equal to zero in computer.Thanks.
Related
So i made this code to check if to integers can be devided without a rest, and its working.
But I needed to make a change so it works. I really just want to understand why this little change completely inversed the outcome of my code. This is the working code
x = input("Erster Teiler")
y = input("Zweiter Teiler")
z = int(x)%int(y)
z1 =int(y)%int(x)
if z == 0 or z1 == 0:
print("teilbar")
else:
print("nicht teilbar")
my first attempt at this excercie is doing the exact oppossite. If i put in 2 numbers that you can not divide, it
says they are divisable.
I just want to know what makes the difference in these codes.
As you can see all i did was changing the premise for my first if-condition.
x = input("Erster Teiler")
y = input("Zweiter Teiler")
z = int(x)%int(y)
z1 =int(y)%int(x)
if z or z1 == 0:
print("teilbar")
else:
print("nicht teilbar")
Check out the section in python documentation on truth value testing
https://docs.python.org/3/library/stdtypes.html
Reproducing some of the documentation
Truth Value Testing
Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below.
By default, an object is considered true unless its class defines either a __bool__() method that returns False or a __len__() method that returns zero, when called with the object. Here are most of the built-in objects considered false:
constants defined to be false: None and False.
zero of any numeric type: 0, 0.0, 0j, Decimal(0), Fraction(0, 1)
empty sequences and collections: '', (), [], {}, set(), range(0)
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.)
if z or z1 == 0:
is testing if z a numeric type any value other than 0 is evaluated to true.
I think your first code was right. In the second code z does not have any condition so that I can't return true or false to execute the if statement. The syntax is wrong
If I have something like a = [1,2,3] and I write a statement like 1 in a == True, that appears to evaluate to false.
However, if I write (1 in a) == True, that evaluates to true.
I am slightly confused about how Python evaluates the first statement to reach false in the end.
Both == and in are considered comparison operators, meaning that operator chaining comes into effect:
Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).
This chaining is what allows you to write:
if 0 <= x < 20: # meaning: if x >= 0 and x < 20:
Hence the expression 1 in a == True is chained as 1 in a and a == True and, since the right side of that and evaluates to false, the entire expression is false.
This chaining does not occur when you "isolate" part of the expression with parentheses, which is why (1 in a) == True acts as you expect.
Having explained that, comparing a boolean value with True (or False for that matter) is not really something you should be doing anyway, since that leads to logically infinite scenarios like:
if (((a == 7) == True) != False) == True # 'a == 7' already a boolean.
Far better just to use one of:
if expression # if comparing with True
if not expression # if comparing with False
I thought I understood these two singleton values in Python until I saw someone using return l1 or l2 in the code, where both l1 and l2 are linked list object, and (s)he wanted to return l1 if it is not None, otherwise, return l2.
This piece of code is good because it is quite short and seems easy to understand. Then, I write some code to figure out what is going one here.
print ( True or 'arbitrary' ) #True
print ( False or 'arbitrary') #arbitrary
print ( None or 'arbitrary' ) #arbitrary
The printed results are as expected. However, when I try to put None and False together. Something really weird happened.
print ( False or None ) #None
print ( None or False ) #False
print ( None or False or True) #True
So, my guess the rules of return A or B are:
return the first True (not None, Not False) value in order (First A and then B)
if there is no True value, then the last value will be returned.
At last, I run this code to verify my guess.
print ( None or False or True or None) # True
print ( None or False or None) # None
print ( False or None or False) # False
The results seem to prove my theory. But anyone has more explanation?
Also, I got something interesting when I use and. Why?
print ( None and False) #None
print ( False and None) #False
The short answer is that 'and' returns the first false value or last true value and 'or' returns the first true or last false answer.
>>> None or False
False
>>> False or None
>>> False and None
False
>>> None and False
...
>>> 0 or 3 or 4
3
>>> 5 and 0 and 6
0
>>> 5 and 0 or 6
6
>>> False or {} or 0
0
>>> 3 and 4 and 5
5
In python an empty string, set, list, dictionary, other container or 0 are all equivalent to False for logical operations. Non-empty collections and non-zero numbers are logically True.
For an 'or' the last expression will be returned if no logically True expression was previously encountered. That expression will logically evaluated by the above rule.
No need to guess. For or, Python's Reference Manual says
"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."
In other words, x if x else y, where x is evaluated just once and y only if needed.
For and, change 'true' to 'false'.
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.
In other words, x if not x else y, where x is evaluated just once and y only if needed.
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)
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.