How To: Logic Expressions


Combining boolean expressions

Sometimes, you'll want to deal with more than one logical expression at a time.

You might like to see if one thing is true and another thing is true, one thing or another thing is true, or maybe see if both things are true.

Python has a few special words to help you do all that: andor, and not.

and

and is a special keyword in Python that figures out whether, given two expressions, both are true. If so, Python will say True; if not, it'll say False. Here's a few examples:

or

or is another special keyword that figures out whether, given two expressions, one or the other or both are true. If so, Python will say True; if not, it'll say False. Here's a few examples:

not

not is Python's last keyword for combining booleans. When you put it in front of something, it negates, or reverses, that expression. So things that were true become false, and things that were false become true. For example:

Challenge

Read through the boolean problems below and try to figure out what Python will return. Run each in the console below if you like.

  1. True and False
  2. True or False
  3. (True or False) and True
  4. (True or False) and True
  5. not False or True
  6. not True and False
  7. not True or False
  8. not True or True

  9. 3 + 3 == 6 and len("hi!") == 3

  10. 3 + 3 == 6 or len("hi!") == 3
  11. 3 + 3 != 6 or len("hi!") == 3
  12. 4 + 4 > 2 and 4 != 5