Boolean means Binary value. It only represents two values either 0 or 1. 1 means True
and 0 means False
. In any programming language, it is necessary to know which statement is true and which statement is false. It is basically used in conditional statements.
In Python, we can evaluate a statement and get the result in Boolean format. Python will show the output when we compare two variables. Examples are given below,
print(5 > 3) #This will return True
print(4 == 7) #This will return False
print(1 < 11) #This will return True
When we run conditional statements, based on the Boolean value it works. For example,
x = 20
y = 30
if y > x: # if this statement is true
print("y is greater than x") # This line will be printed
else: # if this statement is false
print("x is not greater than x") # This line will not be printed
The bool method to change or return a value to Boolean. This method works using the standard truth testing procedure. The syntax of this bool method is bool([value])
i.e. bool[a]. The standard truth testing procedure will be applied if the method takes only one parameter. By default, this method will return False. This method has only two rules. Those are
The method permits us to evaluate any value and returns the output in Boolean format. An example is given below
print(bool("Programming"))
print(bool(20))
#the above two statements return true
We can do the same task above by using variables. For example –
a= "Programming"
b= 20
print(bool(a))
print(bool(b))
#the above two statements return true
There are various conditions where bool()
retunes true. Those are given below
There are various conditions where bool()
retunes false. Those are given below
(), [],
etc.0, 0.0
etc.{}
__bool__() or __len()__
method
a = False
print(bool(a)) # this will return False as a is False
a = True
print(bool(a)) # this will return True as a is True
a=bool(["apple", "cherry", "banana"])
print(bool(a)) # this will return True as a is True
a = 3
b = 7
print(bool(a==b)) # this will return False as a is not equal to b
a = None
print(bool(a)) # this will return False as a is None
a = ()
print(bool(a)) # this will return False as a is an empty sequence
a = {}
print(bool(a)) # this will return False as a is an empty mapping
a = 0.0
print(bool(a)) # this will return False as a is 0
a = “Python”
print(bool(a)) # this will returns True as a is a non-empty string
If we have an object and that object is made from a class with a __len__ function, then it returns False. An example is given below,
class pythonclass():
def __len__(self):
return 0
myclassobject = pythonclass()
print(bool(myclassobject))
#this will return false
The function also can return a Boolean value. Two functions are given below as an example,
def Function1() :
return True
print(Function1())
#This will return True
def Function2() :
return False
if Function2():
print("Yes")
else:
print("no")
#This will print no because the return false