Lets Talk about Bools, Baby: An Intro to Python Logic Part 1 – Boolean Expressions

Welcome back!

I hope you enjoyed your weekend. Today’s lesson is all about Boolean Logic.

We’ve talked about bools before, but lets quickly go over the definition. A boolean expression (or bool for short) can be set to one of two states, True or False. In Python, the words True and False must be capitalized to count as a bool.

These expressions are used to create logical structures in coding. In other words, your programs will be able to make decisions.

To do this, Python uses a few types of boolean operators to sort through and analyze data. These operators follow a specific hierarchy and can be used together. Lets go over each operator in detail.

The “Equal to” Operator: ==

This operator compares two pieces of data to see if they are equal to each other. Here are a few examples.

• 4 == 4
• 4 == 2 + 2
• false == false

To use the equal to operator, we must use the symbol ==. This is because = is used to assign data to variables.

The “Not Equal To” Operator: !=

Similarly to the equal to operator, the not equal to operator compares two pieces of data. Here are a few examples.

• 5 != 6
• 3 != 4 – 2
• true != false

To use the not equal to operator we use the symbol !=. Don’t use something like /= or =/, these will crash your program.

The “Not” Operator: not

The not operator basically switches the value of a boolean expression. For example:

• not True == False
• not False == True
• not 3 ==3 == False

The “And” Operator: and

The and operator compares two pieces of data, if both are True, then it outputs True. Other than that it outputs False. There are a few examples:

• True and True == True
• True and False == False
• False and False == False

The “Or” Operator: or

The or operator compares two pieces of data, if one is True then the output is True. Here are a few examples:

• True or True == True
• True or False == True
• False or False == True

These operators on their own aren’t enough to properly write a logic following program. We’ll get into the other half of Python logic, the if statement, on Wednesday.

One more thing, remember when I mentioned that the operators follow a specific hierarchy? I’ve written the operators in the order that Python prioritizes them by, but I will also create a Pinterest pin explaining operators and ranking them by the end of the day.

If you do go look at that Boolean Operators cheat sheet, check out my other pins as well. They’re full of useful reminders and there are also some motivational quotes that I like to keep in mind while I’m learning something new and run into trouble.

I will see you guys on Wednesday for our next lesson on Python Logic, the if statement.

This site uses Akismet to reduce spam. Learn how your comment data is processed.