Non, True, False, and, or principles in Python | Sololearn: Learn to code for FREE!
Nouvelle formation ! Tous les codeurs devraient apprendre l'IA générative !
Essayez une leçon gratuite
+ 4

Non, True, False, and, or principles in Python

Trying to find some consistency... print(None or False) print(None or True) print(False or True,"\n") print(None and False) print(None and 0) print(False and True,"\n") print(None==False) print(False==0) print(None==0,"\n") print(1 and 0) print(2 and 2) print(2 and 3) print(3 and 2) Output: False True True None None False False True False 0 2 3 2 Can a wiseman comment on that and shed some light on what rules does this follow?

5th Feb 2019, 12:04 PM
Karina Matuszek
Karina Matuszek - avatar
2 Réponses
+ 12
Certain objects evaluate to False, such as False, empty strings, empty sequences (lists, tuples etc.), 0, 0.0 and None. Pretty much everything else is True: strings, numbers that aren't 0, lists/tuples that contain at least one element etc. The "or" operator will return the first object that evaluates to True. That's why "None or False" is False (both None and False are False), but "None or True" is True (None is False, but True is True). "2 or 5" equals 2 because 2 is the first object that evaluates to True (whether 5 is True or False doesn't matter). While "or" has only to find the first True object, "and" has to check all items, because "x and y and z" is only True if all of them are True. So python doesn't know that the whole expression is True before it checks the last object. As soon as the last object is checked and all objects evaluate to True, the last object is returned. That's why "3 and 2" equals 2 (both 3 and 2 are True, but only when the last object (2) is checked, python knows that all objects are True and the last object is returned). Following the same logic, "False or 0" is 0, because now python has to check both objects and both are False. That's why the last object is returned, which is 0.
5th Feb 2019, 1:06 PM
Anna - avatar
+ 1
Thanks Anna, You made it so much easier. So following this logic None and False is evaluated to None since None is the first argument which is evaluated to False, and Python stops at that, and False would be returned if it would stand as a first argument. It does make sense now!
6th Feb 2019, 8:53 AM
Karina Matuszek
Karina Matuszek - avatar