Python Booleans

 

Python Booleans

Boolean consists of only two values; True and False.

 

Why are Boolean’s needed?

Consider the following if-else statement:

x = 13
if(x>13):
    print("X is a prime number.")
else:
    print("X is not a prime number.")

Is it True that X is greater than 13 or is it False?

 

  • Thus Booleans are used to know whether the given expression is True or False.
  • bool() function evaluates values and returns True or False.

 

Here are some examples where the Boolean returns True/False values for different datatypes.

None:

print("None: ",bool(None))

Output:

None:  False

 

Numbers:

print("Zero:",bool(0))
print("Integer:",bool(23))
print("Float:",bool(3.142))
print("Complex:",bool(5+2j))

Output:

Zero: False
Integer: True
Float: True
Complex: True

 

Strings:

#Strings
print("Any string:",bool("Nilesh"))   
print("A string containing number:",bool("8.5"))      
print("Empty string:" ,"")   

Output:

Any string: True
A string containing number: True
Empty string: False

 

Lists:

print("Empty List:",bool([]))
print("List:",bool([1,2,5,2,1,3]))

Output:

Empty List: False
List: True

 

Tuples:

#Tuples
print("Empty Tuple:",bool(()))
print("Tuple:",bool(("Horse", "Rhino", "Tiger")))

Output:

Empty Tuple: False
Tuple: True

 

Sets and Dictionaries:

print("Empty Dictionary:",bool({}))
print("Empty Set:",bool({"Mike", 22, "Science"}))
print("Dictionary:",bool({"name":"Lakshmi", "age":24 ,"job":"unemployed"}))

Output:

Empty Dictionary: False
Empty Set: True
Dictionary: True