1. Truth test
The so-called truth test, refers to when a type object appears in the if or while condition statement, the object value behaves as true or false. Figuring out the truth values in all situations is important to our program.
For an object A, its truth value is defined as:
- True: If the function truth_test (a) returns true.
- False: If the function truth_test (a) returns false.
Take if as an example (while is equivalent, do not repeat), define the function truth_test (x) as:
def truth_test(x): if x: return True else: return False
2. Object's Truth Test
Generally, for an object, the truth test is false if one of the following conditions is true;
- Its built-in function __bool__ () returns false
- Its built-in function __len__ () returns 0
(1) The following type of object Truth test is true:
class X: pass
(2) The following truth test is false:
class Y: def __bool__(self): return False
(3) The following truth test is false:
class Z: def __len__(self): return 0
To enter the Python3 scripting environment, the test process is as follows:
>>> class X:... pass... >>> class Y:... def __bool__(self):... return False... >>> class Z:... def __len__(self):... return 0... >>> def truth_test(x):... if x:... return True... else:...
3. Truth value of common objects
The following is a common case where true truth is false:
- Constant: None and False.
- Value 0 Values: 0, 0.0, 0j, Decimal (0), fraction (0, 1)
- Sequence or set is empty: ", (), [], {}, set (), range (0)
To enter the Python3 scripting environment, the test process is as follows:
>>> truth_test(None)False>>> truth_test(False)False>>> truth_test(0)False>>> truth_test(0.0)False>>> truth_test(0j) #复数False>>> truth_test(Decimal(0)) #十进制浮点数False>>> truth_test(Fraction(0,1)) #分数False>>> truth_test(Fraction(0,2)) #分数False>>> truth_test('')False>>> truth_test(())False>>> truth_test({})False>>> truth_test(set())False>>> truth_test(range(0)) #序列False>>> truth_test(range(2,2)) #序列False
In addition to the other values, the truth test should be true.
4. Some interesting examples
Here are some interesting examples where the principle does not exceed the previous explanation.
>>> if 1 and Fraction(0,1):... print(True)... else:... print(False)... False>>> if 1 and ():... print(True)... else:... print(False)... False>>> if 1 and range(0):... print(True)... else:... print(False)... False>>> if 1 and None:... print(True)... else:... print(False)... False>>> if 1+2j and None:... print(True)... else:... print(False)... False
The truth test in Python3