Python - Booleans
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.
Boolean Values
When an expression is evaluated or two values are compared in Python, it returns the Boolean answer: True or False values.
Example:
In the example below, 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.")
The output of the above code will be:
False x is less than y.
Python bool() function
The Python bool() function returns 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:
- The object is empty, like [], (), {}.
- The object is False
- The object is 0
- The object is None
Syntax
bool(object)
Parameters
object |
Required. Any Python object. |
Example:
In the example below, 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))
The output of the above code will be:
False False False
Example:
In the example below, 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))
The output of the above code will be:
True True True
Boolean return from Functions/Methods
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. See the example below:
MyString = "Hello" print(MyString.isupper()) print(isinstance(MyString, str))
The output of the above code will be:
False True
A user-defined function can also be used to get boolean return. In the example below, 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))
The output of the above code will be:
False