In this article, you will learn about booleans. What boolean is, where, and how we use. I will share examples as many as I can. Boolean is another data type and it is a subclass of integers but they are not the same object. Please have a look following articles before continuing.
Prerequisites:
2- Integers
Bool class is a subclass of integers as I said earlier, therefor all the operators and methods work for integers, will work with booleans too. Besides these, "and" and "or" will work with booleans. Booleans have two constants: "True" and "False". We have seen these terms before. "True" is integer "1" and "False" is an integer "0".
Code:
>>>x = True
>>>print(type(x))
>>>y = False
>>>print(type(y))
Output:
<class 'bool'> <class 'bool'>
As you see, I always write True and False´s first letters capital. What if I write "true"?
Code:
>>>x = true
>>>print(type(x))
Output:
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-2-0acfbe1ec334> in <module>
----> 1 x = true
2 print(type(x))
3 y = False
4 print(type(y))
NameError: name 'true' is not defined
We will get an error message like this. So be careful with that.
Let´s prove other things I said.
Code:
>>>print(True == 1)
>>>print(False == 0)
Output:
True
True
We asked Python if True is equal to 1 and we get a reply back and it says True. Same thing for False, if False equals to 0 and yes it is.
Code:
>>>print(True == 0)
>>>print(False == 1)
Output:
False
False
We asked Python if True is equal to 0 and False equal to 1, no they are not.
Let´s do some other examples:
Code:
>>>print(2<3)
>>>print(2>3)
Output:
True
False
As I said, it works with integer operators. This is simple math. 2 is smaller than 3? yes it is True, 2 is bigger than 3? no it is False.
Besides that, any integers you will use is a True value except "0" (zero).
Code:
>>>bool(0)
Output:
False
Code:
>>>bool(1905)
Output:
True
bool() command converts any value to boolean value by using truth testing procedure. It is like a lie detection :).
Code:
>>>bool(-1905)
Output:
True
Negative values are also "True". Some other languages consider negative numbers as false. But in Python, any integer except zero is "True".
One last example.
Code:
>>>print(True + True)
>>>print(True * True)
>>>print(True * False)
Output:
2
1
0