Javaexercise.com

Python bool() Method

Python bool() method is a built-in method. It returns a boolean value either True or False. In numeric context, True and False represented by 1 and 0 respectivly. It returns False if the argument is not provided or the argument is False. Otherwise it returns True.


Signature

bool([x])

Parameter Description
x (Optional) It is a single argument which can be a numeric, string or other types as well.


Return Value

It returns a boolean value either True or False.


Python bool() Method Example

Let’s first understand, how this method works and what does it return?

#Boolean value
r = bool(True)
print(r)
r = bool(False)
print(r)
#Numeric value
r = bool(1)
print(r)
r = bool(0)
print(r)
#String value
r = bool("Javaexercise")
print(r)
r = bool("")
print(r)
 Output:
 True
 False
 True
 False
 True
 False

As we know, this method takes an argument. So, we applied boolean, numeric and string arguments to check its return value.


Python bool() Method Example: Using List, Tuple and Dictionary

#List
r = bool([1,5,6,8,2,9])
print(r)
#Empty List
r = bool([])
print(r)
#Tuple
r = bool((5,6,9,2,8))
print(r)
#Empty Tuple
r = bool(())
print(r)
#Dictionary
r = bool({0:'Zero',1:'One'})
print(r)
#Empty Dictionary
r = bool({})
print(r)
 Output:
 True
 False
 True
 False
 True
 False

Python bool() Method Example: Using Expressions

We can also use conditional expression which returns boolean value. See the example below.

#Relational operator
r = bool(10<20)
print(r)
#Logical operator
r = bool((10<20) and (10>5))
print(r)
#Logical operator
r = bool((10<20) or (10>5))
print(r)
 Output:
 True
 True
 True