Python for Beginners — Booleans

Is it True or False that in Python or any other programming language Booleans are the most important thing you will learn?

If True:
then you must read this article to learn more about Booleans.

Else:
then leave immediately and read something else.

Let’s debug the code above.

Premise) Booleans are the most important language constructs in Python or any other programming language.

In this article I am going to teach you about Booleans, the most important data type in Python or any other programming language.

It is so important that when you look into the detail of how information is stored on a computer it is mind-blowing!

Did you know that computers store absolutely everything as either 0 or a 1? That’s called binary. 1 is ON, and 0 is OFF. Suffice to know that there is an area in mathematics dedicated to mathematical operations on binary digits, called Boolean algebra, started by George Boole. It was fundamental in the development of electronics and computers. I encourage you to dig deeper though. But it won’t be necessary to follow this tutorial.

So I hope you are convinced that our Premise must be true, and you must therefore read this article until the very last letter. A computer would, right?

Let’s start with the basics

Booleans

A Boolean is a data type that can have two potential values. Either a True or a False.

In Python a Boolean is known as a Bool.

To create a Bool you can simply do:

value = True

or

value = False

simple right?

To ensure we are dealing with an actual Bool we can confirm that using the type function.

print(type(value))
> <class 'bool'>

We can convert any data types in python to a boolean using the bool() function.
This function will return True for almost any data type/value expect the following:

Empty collections: {},[],()

If object is False(Doh…)

If object is None

If object is 0

Let’s test this in a Python terminal

bool(True)
>True
bool(False)
>False
bool(0)
>False
bool(1)
>True
bool({})
>False
>bool([])
False
>bool("")
False

Comparison Operators

We have seen how to create a Boolean out of any data type in Python using the bool() function. But on its own, that is not very useful. A boolean is far more useful if you use it to store comparison operations. But what are comparison operations used for?

Comparison operations are used to compare stuff. Is this number bigger than that number and so on… Is that list equal to that list. Is this monster equal to that monster? Hehehe… just kidding, in python, we can’t compare monsters just yet.
The great thing about comparison operators is that they will also give you a Bool as a result, which you can then store in a variable.

Let me show you some comparison operations that you will see often in python:

# >= bigger than or equal to
print(1 >= 2)
>False
# <= less than or equal to
print(1 <= 2)
>True
# < less than
print(1 < 2)
>False
# == equality
print(1 == 1)
>True
# != different
print(1 != 1)
>False

You might be asking, quite rightly, why can’t we just use = to check if two numbers are equal.

Let’s try that in a python terminal:

value= 1=0
print(value)
> SyntaxError: can't assign to literal

Oops, what happened there?

The python interpreter thought we are trying to assign 0 to 1. But 0 is not a variable, so the python compiler returned an error.

This happened because is used primarily as an assignment operator. An assignment operator allows us to store values in variables. The reason the equality operator is == and not = is to avoid this kind of confusion. The !=, on the other hand, doesn’t clash with = so it doesn’t need doubling down.

The great thing about the comparison operators is that they don’t just apply to numbers. They apply to Strings, Lists, Tuples, Dictionaries, and any class in Python that implements the right methods. I am being vague, I know. But I am going to keep the best for last.

value=[1,2,4]>[1,2,3]
print(value)
>Truevalue="dog"=="cat"
>Falsevalue="dog">"cat"
>True...

Operator Overloading

Without going too academic, this type of thing, where you can use the same operator applied to different data types, is called operator overloading. We are using the same operators to do completely different things, but that are conceptually similar.

You can’t use the same code to compare two numbers as the one you use to compare two strings. Even though it looks like we are using the same code, that’s not the case. Does that make sense?

Ok, maybe not. But you should trust me. If you don’t trust me then I will have to tell you about magic methods. If you read up to here. It is too late. You must find out what magic methods are. But I think you will regret a little bit once I am done explaining them.

Magic methods in Python

To understand what I am saying, you need to know that these comparison operators are just methods with a special syntax. Each data type in Python is a class and each class has a list of functions(methods). If a class supports the comparison operators we saw earlier, the class will implement the following method signatures:

__eq__(self, value) # equals method(==)
__ge__(self, value) # greater or equal method(>=)
__le__(self, value) # less or equal method(<=)
__lt__(self, value) # less thatn method(<)
__gt__(self, value) # greater thanmethod(>)
...

If you have seen methods before in python you will immediately notice the odd __ at the beginning and end of each method name.

These funny looking methods are called magic methods in python. Nothing to do with magic, but somehow someone thought it would be a funky name for them as these methods are called internally without us calling them directly.

So when we do:

1 >= 2

the Python interpreter will convert it to:

1.__ge__(2)

So because 1 is an object of type int, the method__ge__ as defined in the int class will be called.

The reason why it looks like the same code is because each class has a different implementation of the same magic methods.

At this stage, we should take a step back. It is useful to know about magic methods, but in our beginner journey, we shouldn’t get too deep in them as we want first to learn the basics. Suffice to know they exist for now.

In programming, we have to go easy. Some concepts may be hard to sink in, but eventually, they do.

The best thing about magic methods is that they exist but we can pretend they don’t, at least for now.

Conclusion

We have learned how to create a Boolean in Python, how to transform any value of any data type in Python to a Boolean using Python. Also, we have seen how to use comparison operators, and we ended by talking about operator overloading and magic methods.
There is a bit more to cover about Booleans, but I will do it in a separate article. We have to go easy after all.

If you liked this article be sure to check out my new YouYube video where I have a special guest appearance by George Boole, who you must know is no longer living but came back to life thanks to AI!

Resources:

https://en.wikipedia.org/wiki/George_Boole

https://colab.research.google.com/notebooks/intro.ipynb

https://www.w3schools.com/python/python_operators.asp

https://en.wikipedia.org/wiki/Digital_electronics


Posted

in

by

Tags: