In this article, we are going to learn about python bool() function with examples.
Getting Started
Python bool() function is used to convert any value into boolean value i.e. True or False.
Syntax of bool() Function
Syntax of bool() in python is –
bool(value)
Where,
value is argument passed to bool() function.
Parameter of bool() Function
bool() function accepts one parameter –
- value: It’s boolean value is returned.
If no parameter is passed, by default bool() returns False.
Return Value of bool() Function
Python bool() function returns boolean value. So, it’s either True or False.
- True: If argument, value, is any number (except 0) or string.
- False: Few cases where bool() function returns false –
- If a False value is passed.
- If None is passed.
- If an empty sequence is passed e.g. Empty set – (), Empty List – [], Empty Mapping – {} etc.
- If 0 is passed e.g. 0, 0.0 etc.
- If object of Class which have bool() or len() function returns 0 or False
Examples of bool() Function
Now, let’s see some examples of bool() function –
-
Example 1: False value as argument
In this example, we will see some of possible cases where bool() function is accepting value that is considered as False on Truth Testing Procedure.
# Examples of built-in function bool() # that returns False value # Output: False y = False print(bool(y)) # x is not equal to y. So, False x = 5 y = 10 print(bool(x == y)) # Output: False y = None print(bool(y)) # Output: False y = () print(bool(y)) # Output: False y = {} print(bool(y)) # Output: False y = 0.0 print(bool(y))
Output:
False False False False False False
As discussed above, we get False as output in all cases.
-
Example 2: True value as argument
# Examples of built-in function bool() # that returns True value # Output: False y = True print(bool(y)) # x is not equal to y. So, False x = 10 y = 10 print(bool(x == y)) # Output: False y = (1,2,) print(bool(y)) # Output: False y = {'1': "Hello"} print(bool(y)) # Output: False y = 1.0 print(bool(y))
Output:
True True True True True
As discussed above, bool() function returns True in all cases.
Learn more at official doc.
That’s end of our post on python bool() function with examples.