Python Booleans are a type of data that can have one of two possible values: True or False. Booleans are used in logical expressions to determine whether a statement is true or false.
Example
print (10 > 5) #outputs: True print (10 > 15) #outputs: False print (10 == 10) #outputs: True
The Boolean operators and, or & not allows us to check for multiple conditions. For Example:
x = 7
y = 8
print (x > 0 and y == x) #outputs: False
print (x > 0 or y == x) #outputs: True
print (not x > 1) #outputs: False
Python also has a built-in bool()
function that can be used to evaluate any value to a Boolean. For example:
print(bool("Hello")) #True
print(bool(15)) #True
print (bool("")) #False
print (bool(" ")) #True
print (bool(["apple", "cherry", "banana"]) #True
By seeing the above example you may have noticed that almost all values are True. But their are some values that evaluate to False. For example empty values like ()
, {}
, []
, ""
and the number 0
.
Here are the values that will evaluate to False.
print(bool(0))
print(bool(None))
print(bool(""))
print(bool(()))
print(bool({}))
print(bool([]))
print (bool(False))
Remember that ""
and " "
are not same.
Share This Post!