There are many instances in the programming, where a user need a data type which represents True and False values. For this, Python has a bool data type, which takes either True or False values.
When an expression is evaluated or two values are compared in Python, it returns the Boolean answer: True or False values.
In the below example, an expression is evaluated and two values are compared to get the boolean return.
x = 10 y = 25 print(x > y) if x > y: print("x is greater than y.") else: print("x is less than y.")
False x is less than y.
The Python bool() function is used to return boolean value of an object. In Python, everything is an object and when an object is passed as parameter in bool() function, it always returns True unless:
bool(object)
object |
Required. Any Python object. |
In the below example, the bool() function is used on variables called MyString, MyList and MyNumber to return boolean value of these objects. As these objects are either empty or None, hence returns False.
MyString = "" print(bool(MyString)) MyList = [] print(bool(MyList)) MyNumber = None print(bool(MyNumber))
False False False
In the below example, the bool() function is used on variables called MyString, MyList and MyNumber to return True.
MyString = "Hello" print(bool(MyString)) MyList = [1, 2, 3] print(bool(MyList)) MyNumber = 15 print(bool(MyNumber))
True True True
There are many built-in functions and methods in Python which returns a boolean value, like the isupper() method, which is used to check if a string is in uppercase or not. Similarly, the isinstance() function is used to check if an object belongs to specified data type or not. Please see the below example.
MyString = "Hello" print(MyString.isupper()) print(isinstance(MyString, str))
False True
A user-defined function can also be used to get boolean return. In the below example, a user-defined function called equal() is created to compare two values and returns true if values are equal, else returns false.
def equal(a, b): if a == b: return True else: return False print(equal(10,25))
False