Intro to Programming: What Are Booleans in Python?

Let's analyze booleans, comparison operators, and logical operators.
By Ciprian Stratulat • Updated on Mar 2, 2023
blog image

 

Welcome back to our Intro to Programming series. Today I'll talk about booleans, comparison operators, and logical operators in Python.

Let’s start with booleans:

 

 

What Are Booleans?

By definition, a boolean is a data type that can have one of only two possible values: True or False. Booleans are really important for writing computer logic, and they're used to convey whether something (a statement, a variable, a condition, or others) is either True or False.

Portrait of George Boole, founder of boolean algebraImage source: George Boole Wikipedia

Booleans got their name from an English gentleman named George Boole. Boole introduced Boolean algebra in his 1847 book entitled The Mathematical Analysis of Logic. If you're not familiar with Boolean algebra, it's a branch of math that operates not with numbers but with just two values: True and False.

In Boolean algebra, True and False are often represented by the numbers 1 and 0, respectively. Though simple on the surface, Boolean algebra can be very powerful. However, I won't go much deeper into the theory behind it. In computer programming, you're more concerned with its applications, and you'll see them more and more as you progress with this course.

As you might have guessed, booleans help computers understand logic. By allowing you to assign objects, statements, conditions, or other items a value of true or false, booleans make it possible to execute different parts of a given program by an object’s assigned true or false value.
today is December 31
For example, let's consider the statement “today is December 31.” Depending on when you're reading this post, this statement is either True or False. If today is indeed December 31—first of all, I admire your dedication. Second, you would assign this statement a value of True.

Because you can assign a value of either True or False to this statement, a computer can also evaluate it and make a decision based on that statement’s value. The computer can “decide,” for example, to show you a “Happy New Year” message if the statement value is true or show you no message at all if it's False.

 

How Booleans Are Used as True or False Values in Python Code

So, you can already see that booleans are essential when you want to execute a part of our program only when a certain condition is True or False. You'll see exactly how that's possible in upcoming articles, but for now, that's all you need to remember.

As usual, let's look at some code.

Let's create a variable called is_dec_31. I want this variable to store True if the day is indeed December 31 and False otherwise. Let's say today is indeed December 31. In this case, I can type is_dec_31 = True. If I check the data type of this variable using type(is_dec_31), I get bool, which is short in Python for boolean.

# Let's create our variable
is_dec_31 = True

# and let's check our data type
type(is_dec_31)

# When we run this, we will get bool as the output

But what if today is not December 31? In that case, I can make is_dec_31 = False.

I can again check the data type by running type(is_dec_31), and I get bool again.

# Let's change our variable's value
is_dec_31 = False

# Now let's see what data type we have
type(is_dec_31)

# This still returns bool, so we still have a boolean.

One “gotcha” to be aware of is that boolean values in Python need to be capitalized.

If, for example, I write is_dec_31 = true, I get an error. The Python interpreter thinks that this lowercase true is the name of a variable, but it can't find any variable by that name.

So remember, when assigning True or False boolean values, use capitalization. True with a capital T and False with a capital F are the only reserved Python keywords for boolean values.

# If we don't create our boolean with a capital T or F, we get an error
is_dec_31 = true

# This will return the following error:
#NameError Traceback (most recent call last)
#<ipython-input-7-0e9132fa5c15> in <module>()
#----> 1 is_dec_31 = true
#NameError: name 'true' is not defined

 

How to Use Booleans for Evaluating Conditions and Statements

When writing code, you'll rarely work with True and False values directly. Instead, you'll find them as a result of evaluating conditions or other statements.

For example, I can write 1 < 2, which is a mathematical expression that also happens to be valid Python code. When I run this, I get the boolean value True, because 1 is indeed less than 2. In fact, you can check that this expression returns a boolean by running type(1 < 2). Doing so returns bool.

# Let's use a boolean to check an equation
1 < 2
# The output will be True

# Let's check the data type of this equation
type(1 < 2)
# Our output will be bool 

Conversely, you can also ask Python if 1 > 2. Doing so will return the boolean value False. If needed, you can actually assign that result to a variable.

Let's create a variable called condition_is_met and set it to 1 > 2. If I output condition_is_met, you can see that its value is False. You know that's because 1 is not greater than 2. Remember that during variable assignment, the Python interpreter first evaluates the expression to the right of the equal sign, which in this case is 1 > 2.

In this example, I've determined that the evaluation of this expression is False, which Python then assigns to the given variable. The data type of the condition_is_met variable is a boolean, as I can verify by running type(condition_is_met).

# First, let's check our equation
1 > 2
# Our output will be False

# Now let's create a variable for a condition
condition_is_met = 1 > 2
#and run the code
condition_is_met
# Our output will be False

# If we check our data type for our variable
type(condition_is_met)
# We will get bool, since it is either True or False

As I mentioned earlier, in most cases, you won't directly assign the boolean value True or False to a variable. Instead, you'll assign your variable the result of evaluating a boolean expression or condition, which happens to be either True or False.

That's all on booleans for now. Next, I'll cover comparison operators. I already introduced one here, which is the “greater than” sign. I used it to compare two integer numbers. Python defines several such operators that allow you to test whether two objects are the same, are not the same, or whether one object is less than or greater than another object by some given definition.

 

What Are Comparison Operators? 

In past Intro to Programming articles, you've learned about the basic data types in Python. Now, it's time to start exploring how to solve problems using computer programs. To do that, you need to learn how to write computer logic.

 

Are you ready? Let's go!

The first step is a continuation of my boolean discussion. Namely, I'll talk about comparison operators. Comparison operators don’t come with a lot of theory behind them at this point, so I'm going to jump straight into some code. 

You've already seen some of these operators, but in this article, I'll go over all of the ones available to us in Python.

 

How to Use Comparison Operator Less Than or <

To start, you saw previously that you can use the “less than” sign (<) to compare two integers in Python. So, if I write 1 < 2, Python returns the boolean value True, since 1 is indeed less than 2. If I input 2 < 1, however, Python returns False.

By the way, this operator works with strings, too. For example, inputting 'a' < 'b' returns True because 'a' comes before 'b' in alphabetical order. You can use multiple character strings as well. For example, 'water' < 'air' returns False because the first letter 'a' comes before the first letter 'w' in the alphabet.

# If we put in a correct equation, we get True
1 < 2
# Our output is True

# When we try an incorrect equation, we get False
2 < 1
# Our output is False

# We can use < with strings, working in alphabetical order
'a' < 'b'
# Our output is True

'water' < 'air'
# Our output is False, since 'w' comes after 'a'

When using comparison operators, pay attention to the two operands. Operands are the things you're comparing using operators, and they need to be of the same data type.

For example, inputting 2 < '2' will throw an error because you're comparing an integer number on the left to a string on the right. Python doesn't support that. You can, however, compare two strings as you saw before, even if the strings only contain digits in them.

 

For instance, '1' < '2' returns True, and it's important to understand why this is true: it's not because number 1 is less than number 2. Remember that these are both strings. Instead, Python interprets this expression as True because, alphabetically, the string that contains the character 1 comes before the string that contains the character 2.

# If we try to compare an integer with a string
2 < '2'
# We get the following error:
#→---------------------------------------------------------------------------
#TypeError Traceback (most recent call last)
#<ipython-input-6-cbf4b92c1911> in <module>()
#----> 1 2 < '2'
#TypeError: '<' not supported between instances of 'int' and 'str'

# We can compare two strings with integers
'1' < '2'
# Our output is True because alphanumerically, 1 comes before 2

Another small “gotcha” when comparing strings is that capitalization matters.

So, for example, 'Air' < 'air' is True because, in Python, capital letters come before lowercase letters.

# When we run 
'Air' < 'air'
# Our output is True

 

 

How to Use Comparison Operator Greater Than or >

Similar to “less than,” Python also has a “greater than” operator (>). Everything I’ve said about “less than” also applies to “greater than.”

For example, in the simplest form, you can use “greater than” to compare numbers. 2 > 0 returns the boolean value True. Similarly, inputting 'a' > 'b' returns False because ‘a’ comes before ‘b’ alphabetically. Again, you must make sure that the two operands are of the same data type. You can’t use the “greater than” operator to compare strings with integers, for example.

To recap, the objects being compared are the operands, and the sign used to compare them is the operator.

# We can use the greater than symbol as well
2 > 0
# Our output will be True

'a' > 'b'
# Our output will be False

 

Article continues below

How to Use the Comparison Operator Equal to or ==

To check for equality, you can use two equal signs next to each other, like so: 1 == 1. This expression returns the boolean value True.

Let's try another one. 1 == 2 returns False. Why? Because 1, obviously, is not equal to 2. We must use two equal signs instead of a single equal sign because Python reserves the single equal sign for variable assignment.

To Python, writing 1 = 2 indicates that you're actually trying to assign the value 2 to the integer number 1. Notice that this 1 here is not a variable but an integer value. However, you can't redefine the value of 1, so this expression yields an error. More specifically, Python returns a syntax error.

# We use two equals signs, ==, to show equality
1 == 1
# Our output is True

# If we try to only use one sign
1 = 2
# We get the following error:
#   File "<ipython-input-15-c0ab9e3898ea>", line 1
#1 = 2
#ˆ
#SyntaxError: can't assign to literal

Beginner coders occasionally get confused by this. In the beginning, it's easy to confuse the single equal sign with the double equal, and this will cause the Python interpreter to complain. So, remember that one equal sign is for assignment and two equal signs are for comparison.

You can also use this comparison operator to check if two strings are equal. For example, you can check if lowercase 'air' is equal to lowercase 'air' by writing 'air' == 'air'. And, of course, it is. But remember that capitalization matters for strings.

You may hear programmers often say that strings are case-sensitive. So, if you compare the capitalized string 'Air' with the lowercase 'air' by writing 'air' == 'Air', you'll get the boolean value False because the two strings are not the same. For two strings to be the same in Python, they must have the exact same characters, capitalization, and all.

# We can check if strings are equal
'air' == 'air'
# Our output is True

'Air' == 'air'
# Our output is False, because Python is case sensitive

Again, be careful about data types. If you check if the integer number 1 is equal to the string that consists of the character 1, you'll get a False. That's because one of the operands is an integer and the other is a string. A number cannot be equal to a string.

# Pay attention to data types
1 == '1'
# Our output is False because we have a number and a string

You can also use the == operator to compare lists. According to Python, two lists are equal if they contain the same items and those items are listed in the same order.

This requirement exists because lists are ordered sequences. For example, in Python, the list [1,2] is equal to the list [1,2]. These lists have the same items, and the items are in the same order. In contrast, in Python, the list [1,2] is not equal to the list [2,1]. Even though these two lists have the same items, their items are in a different order. In Python, the second list is considered a different list.

# Let's compare lists
[1,2] == [1,2]
# Our output is True because the lists have the same items in the same order

[1,2] == [2,1]
# Our output is False because the items are not in the same order

 

How Is the Equal Comparison Operator Used for Dictionaries in Python? 

What about dictionaries? You know from previous posts that, unlike lists, dictionaries are not ordered. As long as dictionaries have the same pairs, the order in which the pairs are typed doesn't matter to the Python interpreter.

For example, if you input {'a': 1, 'b': 2} == {'b': 2, 'a': 1}, Python will return the boolean value True because these notations between each set of curly brackets essentially represent the same dictionary. But, inputting {'a': 1, 'b': 2} == {'a': 1, 'b': 3} will return False.

While these two dictionaries do have the same keys, their values are different. Notice that in the second dictionary, the string key 'b' is mapped to the integer number 3, not 2.

# Let's compare some dictionaries
{'a' : 1, 'b' : 2} == {'b' : 2, 'a' : 1}
# Our output is True because dictionaries aren't ordered

{'a' : 1, 'b' : 2} == {'a' : 1, 'b' : 3}
# Our output is False because the values are different

 

How to Use Comparison Operators with Variables

Comparison operators also work with variables.

 

Let's create a variable a and assign it to the integer number 2. Using comparison operators, you can compare, for example, the value stored in a with the integer 0. To do so, we run a > 0.

In this case, Python returns the boolean value True because a stores the integer number 2, and 2 is greater than 0. Trying again, I can ask if the value stored is less than 1. Running a < 1 will return False because 2 is not less than 1. Trying again one last time, I ask if a is equal to the integer value 3. The answer, of course, is  False. As Python tells us, the integer 2 is not equal to 3.

# Let's try comparing variables
a = 2

a > 0
# Our output is True

a < 1
# Our output is False

a == 3
# Our output is False

In these comparisons, both of the operands can also be variables. Let's try this out.

If I have another variable named b and set that equal to 1, I can check if the value I previously stored in a is greater than the value stored in b. To make this comparison, I type a > b.

As you might be able to guess, Python returns True because a stores the integer value 2 and b stores the integer value 1, and, of course, 2 is greater than 1. Comparing the variables a and b is not the same as comparing ‘a’ and ‘b’ as two strings. Comparing the two letters as strings in Python reveals that a variable that contains the character 'a' is not greater than the string that contains the character 'b'. This is because the character “a” comes before the character “b” alphabetically.

# Let's add a second variable
b = 1
a > b
# Our output is True, because 2 > 1

# Remember, variables do not use quotation marks
'a' > 'b'
# Our output is False, because these are strings

This again might be a little confusing in the beginning, so it's always a good idea to keep track of the data type of each object you're dealing with. In the first case above, I know that a is a variable name, which actually stores an integer number. But in the second case, 'a' is a string that contains a single character: the letter “a”. Making this distinction is important.

 

How to Use Comparison Operator Not Equal or !=

The next comparison operator I'll cover is “not equal.” This operator will return True if two objects are not equal and False if they're equal, and its notation in Python is !=

Here's a quick example: running 2 != 1 will return True because 2 is not equal to 1. Under the same logic, running 1 != 1 will return False because 1 is, in fact, equal to 1.

And again, this operator also works with strings. Running 'Air' != 'air' will return True because the two strings use different capitalizations. As discussed before, different capitalizations between objects will cause the Python interpreter to see them distinctly.

# Let's look at not equal, or !=
2 != 1
# Our output is True

1 != 1
# Our output is False

'Air' != 'air'
# Our output is True, because one includes an uppercase letter

 

How to Use the Comparison Operator Less Than or Equal or <=

Another operator you can use is “less than or equal,” which is written using a less than sign immediately followed by a single equal sign, <=.

For example, to use “less than or equal,” I write 1 <= 2.

In this case, Python returns True, and it does the same when I try 1 <= 1. Like the others, this operator also works with strings: 'air' <= 'water' is True because 'water' comes after 'air' alphabetically. Similarly, 'air' <= 'air' is also True because the two strings are equal.

# Let's look at less than or equal to
1 <= 2
# Our output is True

1 <= 1
# Our output is still True

'air' <= 'water'
# Our output is True

'air' <= 'air'
# Our output is still True

 

How to Use the Comparison Operator Greater Than or Equal or >=

Finally, you also have a “greater than or equal” operator. Running 3 >= 0 in Python will return True and so will 0 >= 0. Notice that for both “less than or equal” and “greater than or equal” operators, a single equal sign comes after the less than or greater than sign.

# Let's take a look at greater than or equal to
3 >= 0
# Our output is True

0 >= 0
# Our output is still True

By now, I've gone over all of the comparison operators available in Python. Comparison operators allow you to compare objects, which is a task that you ask computer programs to do all of the time. As always with new concepts, practice is key to mastery. Spend some time playing with these operators on your own and try out different situations.

 

What Are Logical Operators in Python? 

In the last two sections, I'll go over logical operators. While the name might seem intimidating, don't worry. In fact, you've already used logical operators when making decisions for yourself. You probably just didn't know them by this name.

In this section, I'll go over the logical operators AND, OR, and NOT.

Fundamentally, logical operators allow you to combine comparisons, and you'll use them all the time.

For example, if you tell yourself, “I'll go out if it's Friday and the weather is nice,” you're using the logical operator AND to combine two comparisons.

Let's break that example down further:

The first comparison looks at the current day of the week. As humans, you (usually) store the name of the current day of the week somewhere in your memory. The mechanics of how that information is placed into our memory is irrelevant for this example. Maybe you read it on your phone, or maybe you deduced it by remembering the day of the week it was yesterday. But because the current day of the week is stored in our memory, at any given time, you have the ability to evaluate whether the phrase “the current day of the week is Friday” is either true or false.

Perhaps you make your evaluation by comparing the name of the current day of the week with the word “Friday.” If they match, you know that the current day is a Friday. And if they don't, you know that today is not Friday. Of course, when asked, “Is today Friday?”, you're able to give an answer immediately. In fact, you're not usually aware of this comparison process as it happens automatically in your mind.

If you were to write this example in computer code, you would probably have a variable called current_day_of_week. In your variable, you'd store a string that tells you what day of the week it is, and you'd compare the value of that variable with the string 'Friday'.

The second condition in our combined comparison depends on whether or not the weather outside is “nice.” This condition is more complex because the concept of nice weather is subjective.

While most people prefer sunny weather, others may like rain, and even others may get more specific and require their “nice” weather to have a temperature above 70° and below 90°. For the purpose of this example, how others personally define nice weather doesn’t matter. Ultimately, the comparison is to see if your definition of nice weather is met. To simplify things, you can assume that nice weather means that the current temperature is greater than 70°F.

In code, you can write this comparison using a variable that stores the current_temperature as an integer. Then, you can compare our variable to the integer 70. The current_temperature value may be set by a variety of methods.

Maybe the computer reads the temperature from a remote thermometer, or maybe it gets it from the Internet. How it happens doesn't really matter. Once you establish a way to get the value of the current temperature and store it into our variable, you're ready to combine our comparisons.

 

How to Use the Logical Operator AND

The logical operator AND allows you to combine our two conditions and follow through with an action only if both of your conditions are met.

In Python, you might write something like go_out = current_day_of_week == 'Friday' and current_temperature > 70.

Here, you begin to see the importance of boolean values. Each of these comparisons can be evaluated by Python to equal either True or False, as you learned earlier. But now, you can use logical operators to combine those True and False values to get the True or False value for the overall condition you're trying to express.

In this example, go_out will store the value True if both current_day_of_week == 'Friday' is True and current_temperature > 70 is True. If either of those conditions equals False, the variable go_out will also be False, and consequently, you won't go out.

Knowing this, you can move on to the truth table for the logical operator AND. A truth table tells us the conditions under which the AND logical operator will return the value True. And from the previous example, you might know intuitively that the only case when the AND logical operator will return True is when all conditions used with AND are true. You can see here that if any of the individual conditions are False, then the overall condition will also be False.

George Boole, by the way, was the first person to formalize the use of logical comparison operators, which is why booleans were named after him. However, humans have been using this kind of logic for a long time before him. Our minds have an amazing complexity that enables us to make logical evaluations implicitly while also sometimes causing difficulty in expressing our thoughts in easy-to-follow steps. And the latter, in my opinion, makes programming hard for people to learn in the beginning.

This difficulty in learning to program does not lie in the syntax or the quirks of specific programming languages. Instead, the difficulty is that we're not used to breaking down our reasoning and expressing it clearly. When you write code, you absolutely have to do this because machines, frankly, are still pretty dumb. In order to complete operations successfully, machines must be told what to do in very small and easy-to-follow steps.

 

Let's go back to logical operators.

So far, I've discussed one example where you combined two conditions. But of course, you can also use logical operators to combine as many conditions as a given situation needs. Let's imagine another example.

Let’s say that I’ve decided that I’ll meet my friend if it’s after 6 pm, and I’m free, and I don’t have a headache. Here, I’m using two AND logical operators to combine three conditions, and I'll only meet my friend if all three of these conditions are True

 

How to Use the Logical Operator OR

The logical operator AND will return True if—and only if—all comparisons or conditions it combines are True
Let's look at the second logical operator I want to cover in this post: OR.

As usual, I'll start with an example.

Take the phrase, “I'll meet with friends on Saturday or Sunday.” In order to determine whether or not you should meet with friends, you need to do two comparisons.

The first one compares the current day of the week with the string 'Saturday'.

The second one compares the current day of the week with the string 'Sunday'.

To make these comparisons in Python, you can write this as meet_with_friends = current_day_of_week == 'Saturday' or current_day_of_week == 'Sunday'. If any one of these comparisons is True, then the variable meet_with_friends will also store the boolean value True.

The OR logical operator is similar to the AND logical operator in that it combines comparisons and returns a boolean value. The important difference is that while the AND logical operator returns True if all of the combined comparisons are True, the OR logical operator returns True if at least one of the comparisons is True. This, in turn, gives you the following truth table. Similar to the AND logical operator, you can combine as many comparisons or conditions as you want using OR.

 

How to Use the Logical Operator NOT

Finally, let's briefly talk about NOT. The NOT logical operator is used for negation, as the keyword implies. In other words, NOT is used to express conditions that are met when a comparison is False. For example, let’s look at the following sentence: “The weather is nice if the temperature is not below 70.” You can choose from one of two ways to express this.

The first way is to rephrase this sentence to say that the weather is nice when the temperature is greater than or equal to 70. If you think back to the previous example and assume that you have a variable that stores the current temperature, you can write this in Python as weather_is_nice = current_temperature >= 70. This code would definitely match the condition you expressed.

But sometimes, rephrasing the comparison in your head can be more complicated. For those scenarios, you can use the NOT logical operator.

In Python, you have the option to use the NOT logical operator to express the original condition of “The weather is nice if the temperature is not below 70” as weather_is_nice = not current_temperature < 70.

The truth table for the NOT logical operator is actually quite simple, and you can see it here. The table shows that NOT True is equal to False and NOT False is equal to True.

I wanted to show with these examples that this process of expressing and evaluating logical operators is not something new at all. In fact, as humans, we can do it easily, and we do it naturally all the time. Yet, the ability to express the use of logical operators in computer code is part of why programming is such a powerful tool. A good mental exercise is to take some of the conditions you think of or express daily and write them as comparisons linked by logical operators.

For this exercise, assume you have variables available that store important pieces of information. These variables may store current time, current day, or current temperature, to name a few examples. Write your comparisons with logical operators on a piece of paper, and see if they make sense.

That's all for the logical operators AND, OR, and NOT. In my final section, I'll explore how you can use these logical operators to write Python code.

 

How to Use Logical Operators in Python Code

Let’s take a look at the three logical operators, AND, OR, and NOT, in action with a few more examples.

Let's assume that you have a variable that stores the current day of the week. You'll make that variable equal to the string ‘Thursday’.

 

How to Use the Logical Operator OR

Using the OR variable, you can write the comparison is_weekend = current_day_of_week == ‘Saturday’ OR current_day_of_week == ‘Sunday’. If you check the variable is_weekend, you'll see that it’s False. That’s because the string 'Thursday' doesn't equal the string 'Saturday', and it also doesn't equal the string 'Sunday'.

# Let's define our variable
current_day_of_week = 'Thursday'

# Now let's write our comparison
is_weekend = current_day_of_week == 'Saturday' or current_day_of_week == 'Sunday'

# Let's check our comparison
is_weekend
# Our output is False

Let’s go back and change current_day_of_week to 'Saturday' and rerun my example.

# Let's update our variable
current_day_of_week = 'Saturday'
# and rerun our example
is_weekend
# Our output is True

You see that now is_weekend stores the boolean value True because the first of the conditions is true. That is to say that current_day_of_week stores the string 'Saturday'.

A best practice, in general, is to wrap comparisons in parentheses to organize the code more clearly. I recommend that you do so with your code as well. Following this convention, you'd rewrite this example as is_weekend = (current_day_of_week == 'Saturday') or (current_day_of_week == 'Sunday').

# Let's make our code cleaner
is_weekend - (current_day_of_week == 'Saturday') or (current_day_of_week == 'Sunday')
is_weekend
# Our output is still True, but our code looks better

 

How to Use the Logical Operator AND

Let's make this a bit more complex. Let's assume that you can ask a user whether they feel good or bad, and you can store their answer in a boolean variable. Let's call this variable user_feels_good. When the user tells us that, indeed, they feel good, you'll set user_feels_good to the boolean value True. But how would you express the question, “Is it a weekend and does the user feel good?” The answer is pretty simple: you'd type is_weekend and user_feels_good.

Hypothetically, these comparisons could be a condition for meeting with friends. If that’s the case, you can say meet_friends = is_weekend and user_feels_good to store your result into a variable meet_friends. If you print out meet_friends, you'll see that it's True because the user told us they feel good and it is indeed the weekend. (At least it is in our example since you set current_day_of_week to be Saturday above.) By the way, you could also express this comparison in a single line as meet_friends = (current_day_of_week == 'Saturday') or (current_day_of_week == 'Sunday') and user_feels_good. Doing so, you can, again, output meet_friends and see that it's still True.

# Let's add another variable
user_feels_good = True

# Let's set our conditions
meet_friends = is_weekend and user_feels_good
meet_friends
# Our output is True

#We could combine these conditions on the same line:
meet_friends = ((current_day_of_week == 'Saturday') or (current_day_or_week == 'Sunday)) and user_feels_good
meet_friends
# Our output is still True

 

How to Use the Logical Operator NOT 

Finally, let me show you one more example of the NOT logical operator in action. Let's say that we now want to create a user_feels_bad variable that is basically the opposite of user_feels_good. In other words, this variable will indicate that the user feels bad when they don't feel good. I can write that as user_feels_bad = not user_feels_good. So now, if I output user_feels_bad, I see that it's False, and that's because the variable user_feels_good was set to True above.

# Let's add a NOT variable
user_feels_bad = not user_feels_good
user_feels_bad
# Our output is False

Of course, the NOT logical operator can be used to negate much more complex conditions. For example, I’ll write not (1 == 1 or 'a' == 'b'). Let's go over this and break it down.

First, we must evaluate what's inside the parentheses first because they have the highest priority, as we saw. Because 1 indeed does equal 1 and the OR logical operator needs at least one of the conditions to be True, the whole phrase within the parentheses evaluates to True. This expression is equivalent to NOT True, which, of course, is False.

# Let's try another NOT example
not (1 == 1 or 'a' == 'b')
# Our output is False because the code inside the parentheses is True

If you're ready for a bit of philosophy, check this out: not (True == False). If I run this, I get True. This is essentially a way of asking the question, “Is it true that truth and falsehood are not the same?” And the answer is, of course, that it is true.

# Let's try our philosophical example
not True
# Our output is False

not (True == False)
# Our answer is True

 

A Note on How to Use Parentheses with Boolean Variables in Python 

I want to point out a couple of things here. First, note that you don't need to wrap single boolean variables in parentheses. In the example, I did not use parentheses around user_feels_good. Second, notice how I wrapped everything to the left of and in parentheses. That's because I consider that whole segment of code a condition by itself.

Parentheses are important, and where you place them matters because they change the order in which conditions are evaluated. Let me show you why.

Let's say I have this condition: (1 == 3 and 1 == 1) or ('a' == 'a'). These conditions will return True because the first condition, 1 == 3 and 1 == 1, returns False, but the second condition, 'a' == 'a', returns True. You know that the logical operator OR will return True if at least one of the conditions is True.

# Let's break these parentheses down:
(1 == 3 and 1 == 1) or ('a' == 'a')
# Our output is True, because while part one was False, part two was True
# The OR here allows this to be True

Compare that with the condition (1 == 3) and (1 == 1 or 'a' == 'a'). Here, you only shifted the parentheses, but this condition will return False. Why is that?

Remember that Python will always evaluate the code in parentheses first. In this example, if you look at the first set of parentheses that has the single comparison 1 == 3, you see that it is obviously False. The second set of parentheses in my example evaluates to True because an OR will have a True result as long as any of its comparisons is True.

In this case, both comparisons evaluate to True. Putting it together, the whole expression evaluates to False AND True, which is ultimately False. The AND logical operator requires all conditions to be True for the result to be True.

# Let's break these parentheses down
(1 == 3) and (1 == 1 or 'a' == 'a')
# This is False, because the first part is False
# The AND makes this False

In this example, the parentheses completely altered the conditions. When using logical comparisons, be careful that you put your parentheses where you actually intend them to be. Otherwise, subtle bugs may creep into your code, and it could take you a long time to find them.

 

So, that's it for logical operators. It may feel strange in the beginning to express conditions this way, but practice will make it second nature. As you start writing more complex problems, logical operators will become indispensable. But for now, just remember that you can use logical operators to combine comparisons in order to express more complex conditions. You use the AND logical operator when you want all conditions to be true and the OR logical operator when you want at least one condition to be true. You use the NOT logical operator to get the opposite truth value, so when you want False instead of True and True instead of False.

 

Ciprian Stratulat

CTO | Software Engineer

Ciprian Stratulat

Ciprian is a software engineer and the CTO of Edlitera. As an instructor, Ciprian is a big believer in first building an intuition about a new topic, and then mastering it through guided deliberate practice.

Before Edlitera, Ciprian worked as a Software Engineer in finance, biotech, genomics and e-book publishing. Ciprian holds a degree in Computer Science from Harvard University.