The python data type bool
is used to store two values i.e True
and False
.
Bool is used to test whether the result of an expression is true or false.
To check the boolean value of an expression or a variable, pass it as a parameter to the bool function:
print(bool(expression))
or
print(expression)
Bool can be used when there is a need to compare two or more values.
Here is the list of various comparison operators:
x == y # x is equal to y
x != y # x is not equal to y
x > y # x is greater than y
x < y # x is less than y
x >= y # x is greater than or equal to y
x <= y # x is less than or equal to y
#check if x and y are equalprint(3==4)print(bool(3==4))#check if x and y are not equalprint(3!=4)print(bool(3!=4))#check if x is greater than yprint(3>4)print(bool(3>4))#check if x is less than yprint(3<4)print(bool(3<4))#check if x is greater than or equal to yprint(3>=4)print(bool(3>=4))#check if x is less than equal to yprint(3<=4)print(bool(3<=4))
Note: If an empty list, empty array, empty sequence, None, False, 0 or 0.0 is passed as a parameter to bool function it will always return false.
The following code checks if the number passed to the bool
function is divisible by 3. It returns true if the value is divisible by 3 and false otherwise.
x=9if(bool(x%3==0)):print(x,"is divisble by 3")else:print(x,"is not divisble by 3")
Free Resources