How To: Logic Expressions


Boolean expressions

"Boolean expressions" is a semi-fancy way to refer to snippets of code that result in a boolean; things like the 7 < 0 that we talked about in the last section are "boolean expressions."

Boolean operators

Just like the addition (+), subtraction (-), multiplication (*), and division (/) operators for math problems, boolean problems have their own operators:

  • >: greater than
  • <: less than
  • >=: greater than or equal to
  • <=: less than or equal to
  • ==: equivalent
  • !=: not equivalent

There's a few examples in the console below. Try out your own, too, if you like:

Two equals signs in a row?

You might find it odd that == stands in for "equivalent to", rather than =. That's because a single equals sign (=) has its own meaning, which we'll talk about with variable containers in an upcoming lesson.

When we talk about whether two things are or are not equivalent in Python, we have to use two characters – either == or !=.

Using boolean operators

When you use a boolean operator, you're really asking Python whether the phrase you're typing is true or false. You can nearly play the dialogue in your head:

"3 + 3 > 7?"

"Nope, 3 + 3 isn't greater than 7, so that's False."

"How about 3 + 3 == 6?"

"Yeah, 3 + 3 is equivalent to 6, so that one's True."

Challenge

Use the console above to create:

  1. A boolean expression that includes the "greater than" symbol
  2. A boolean expression that includes the "less than" symbol
  3. A boolean expression that includes the "greater than or equal to" symbol
  4. A boolean expression that includes the "less than or equal to" symbol
  5. A boolean expression that includes the "equivalent" symbol
  6. A boolean expression that includes the "not equivalent" symbol