Boolean Practice Python
The logic combinations you learned from the last exercise are called “boolean” logic expressions. Boolean logic is used everywhere in programming. They are essential fundamental parts 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 out what you think the answer will be. In each case, it will be either True or False.
1. True and True
2. False and True
3. 1 == 1 and 2 == 1
4. "test" == "test"
5. 1 == 1 or 2 != 1
6. True and 1 == 1
7. False and 0 != 0
8. True or 1 == 1
9. "test" == "testing"
10. 1 != 0 and 2 == 1
11. "test" != "testing"
12. "test" == 1
13. not (True and False)
14. not (1 == 1 and 0 != 1)
15. not (10 == 1 or 1000 == 1000)
16. not (1 != 10 or 3 == 4)
17. not ("testing" == "testing" and "Zed" == "Cool Guy")
18. 1 == 1 and not ("testing" == 1 or 1 == 0)
19. "chunky" == "bacon" and not (3 == 4 or 3 == 3)
20. 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:
Practice
$ python
Python 2.5.1 (r251:54863, Feb 6 2018, 19:02:12)
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> True and True
True
>>> 1 == 1 and 2 == 2
True
Study Drills
- There are a lot of operators in Python similar to != and ==. Try to fi nd out as many “equality operators” as you can. They should be like < or <=.
- Write out the names of each of these equality operators. For example, I call != “not equal.”
- Play with the Python by typing out new boolean operators, and before you hit Enter, try to shout out what it is. Do not think about it—just name the first thing that comes to mind. Write it down, then hit Enter, and keep track of how many you get right and wrong.
- Throw away the piece of paper from #3 so you do not accidentally try to use it later.
Why does “test” and “test” return “test” or 1 and 1 return 1 instead of True?
Python and many languages like it return one of the operands to their boolean expressions rather than just True or False. This means that if you did False and 1, then you get the first operand (False), but if you do True and 1, then you get the second (1).
Is there any difference between != and <>?
Python has deprecated <> in favor of !=, so use !=. Other than that, there should be no difference.
Isn’t there a shortcut?
Yes. Any and expression that has a False is immediately False, so you can stop there. Any or expression that has a True is immediately True, so you can stop there. But make sure that you can process the whole expression, because later it becomes helpful.