Python for Beginners — Booleans

Armindo Cachada
Sep 24 · 6 min read
Image for post
Image for post
Photo by Michael Dziedzic on Unsplash

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

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

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)
>True
value="dog"=="cat"
>False
value="dog">"cat"
>True
...

Operator Overloading

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:

The Startup

Medium's largest active publication, followed by +730K people. Follow to join our community.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store