Video Coming Soon...
29: Boolean Practice
The logic combinations you learned from the last exercise are called "Boolean" logic expressions. Boolean logic is used everywhere in programming. It is a fundamental part of computation, and knowing them very well is akin to knowing your scales in music.
In this exercise you will take the logic exercises you memorized and start trying them out in Python. Take each of these logic problems and write what you think the answer will be. In each case it will be either True or False. Once you have the answers written down, you will start Python in your terminal and type each logic problem in to confirm your answers.
True and TrueFalse and True1 == 1 and 2 == 1"test" == "test"1 == 1 or 2 != 1True and 1 == 1False and 0 != 0True or 1 == 1"test" == "testing"1 != 0 and 2 == 1"test" != "testing""test" == 1not (True and False)not (1 == 1 and 0 != 1)not (10 == 1 or 1000 == 1000)not (1 != 10 or 3 == 4)not ("testing" == "testing" and "Zed" == "Cool Guy")1 == 1 and (not ("testing" == 1 or 1 == 0))"chunky" == "bacon" and (not (3 == 4 or 3 == 3))3 != 3 and (not ("testing" == "testing" or "Python" == "Fun"))
I will also give you a trick to help you figure out the more complicated ones toward the end.
Whenever you see these Boolean logic statements, you can solve them easily by this simple process:
- Find an equality test (== or !=) and replace it with its truth.
- Find each
and/orinside parentheses and solve those first. - Find each
notand invert it. - Find any remaining
and/orand solve it. - When you are done you should have True or False.
I will demonstrate with a variation on #20:
3 != 4 and not ("testing" != "test" or "Python" == "Python")
Here's me going through each of the steps and showing you the translation until I've boiled it down to a single result:
Solve each equality test:
3 != 4isTrue, so replace that withTrueto getTrue and not ("testing" != "test" or "Python" == "Python")"testing" != "test"isTrueso replace that withTrueto getTrue and not (True or "Python" == "Python")"Python" == "Python"is True so replace that withTrueand we haveTrue and not (True or True)
Find each
and/orin parentheses ():(True or True)isTrueso replace that to getTrue and not (True)
Find each
notand invert it:not (True)isFalseso replace that and we haveTrue and False
Find any remaining
and/orand solve them:True and FalseisFalseand you're done.
With that we're done and know the result is False.
Register for Learn Python the Hard Way, 5th Edition (2023-2024)
Register today for the course and get the all currently available videos and lessons, plus all future modules for no extra charge.