In programming, sometimes we want values to be either True or False which has assigned in programming as Boolean values.
We can compare two values directly which will return True or False accordingly as a Boolean value.
Example
print(10 == 10)print(10 == 9)print(10 > 9)print(10 < 9)
Output
TrueFalseTrueFalse
In Python, we use the bool() function to check True or False.
bool() function always returns True until we don’t pass something from the following–
- 0
- empty string
- empty list, tuple, dictionary
- other empty objects like a set
- anything like a function that returns a function
Example
print(bool(0)) # passing 0print(bool("")) # passing an empty stringprint(bool([])) # passing an empty listprint(bool({})) # passing an empty dictprint(bool(())) # passing an empty set
Output
FalseFalseFalseFalseFalse
bool() will return True if the value is not an empty one.
Example
print(bool(1))print(bool(12.2))print(bool(23j))print(bool("aString"))print(bool([1, 2, "Hello"]))print(bool({"Key":"value"}))
Output
TrueTrueTrueTrueTrueTrue