The bool() function converts the given value to a boolean value (True
or False
). If the given value is False, the bool function returns False else it returns True.
Syntax of bool() function
bool([value])
bool() function parameters
As we seen in the syntax that the bool() function can take a single parameter (value that needs to be converted). It converts the given value to True or False.
If we don’t pass any value to bool() function, it returns False.
Return Value from bool()
This function returns a boolean value.
This function returns False for all the following values:
1. None
2. False
3. Zero number of any type such as int, float and complex. For example: 0, 0.0, 0j
4. Empty list [], Empty tuple (), Empty String ”.
5. Empty dictionary {}.
6. objects of Classes that implements __bool__() or __len()__ method, which returns 0 or False
This function returns True for all other values except the values that are mentioned above.
Example: bool() function
In the following example, we will check the output of bool() function for the given values. We have different values of different data types and we are printing the return value of bool() function in the output.
# empty list lis = [] print(lis,'is',bool(lis)) # empty tuple t = () print(t,'is',bool(t)) # zero complex number c = 0 + 0j print(c,'is',bool(c)) num = 99 print(num, 'is', bool(num)) val = None print(val,'is',bool(val)) val = True print(val,'is',bool(val)) # empty string str = '' print(str,'is',bool(str)) str = 'Hello' print(str,'is',bool(str))
Output:
Leave a Reply