Boolean values in Python are represented as two constants True and False.
True and False constants are simply set to integer values of 1 and 0, i.e True is represented as 1 and False is represented as 0. In simple way, True and False are alternative ways to spell integer values 1 and 0.
Note: True should have uppercase ‘T’ and False should have uppercase ‘F’. Using a lowercase t and f throws error.
The type object for this new type is named bool.
x = True print(type(x))
Output
<class 'bool'>
Arithmetic operation using a Boolean in Python
The Boolean type is a subclass of int class, so we can perform arithmetic using a Boolean.
t = True
f = False
print('t + 1 = ',t + 1)
print('10 - t = ',10 - t)
print('10 - f = ',10 - f)
print('10 * f = ',10 * f)
print('5/t = ', 5/t)
print('f/t = ', f/t)
Output
t + 1 = 2
10 - t = 9
10 - f = 10
10 * f = 0
5/t = 5.0
f/t = 0.0
Integers, Floats and String as Boolean
Numbers can be converted to boolean type using Python’s bool() function.
Pretty much everything which has a content evaluates to True.
An integer, float or complex number having value 0 returns False. An integer, float or complex number set to any other number, positive or negative, returns True.
print("bool(0): ", bool(0))
print("bool(1.5): ", bool(1.5))
print("bool(-5): ", bool(-5))
print("bool('hello'): ", bool("hello"))
print("bool(['Sunday','Monday']): ", bool(['Sunday','Monday']))
Output
bool(1.5): True
bool(-5): True
bool('hello'): True
bool(['Sunday','Monday']): True
Empty value evaluates False
print('bool(False): ', bool(False))
print('bool(None): ', bool(None))
print('bool(0): ', bool(0))
print('bool(""): ', bool(""))
print('bool(()): ', bool(()))
print('bool([]): ', bool([]))
print('bool({}): ', bool({}))
Output
bool(False): False
bool(None): False
bool(0): False
bool(""): False
bool(()): False
bool([]): False
bool({}): False
