Programming logical problems in Python
A comparison operation compares two values and returns a bool result: True or False. The operations are: == (equal), != (not equal), < (less), > (greater), <= (less or equal), >= (greater or equal). Note that = is assignment and == is comparison, so do not mix them up. Logical operations are used for a compound condition: and is True if both conditions are True; or is True if at least one is True; not turns the result to its opposite. The order is: first comparison, then not, then and, and or last; use brackets when in doubt. The in operation checks whether a substring is inside a string, and capital and small letters are different: "kit" in "kitob" is True, "Kit" in "kitob" is False. Strings can also be compared with == and <, and they are compared by the codes of the letters.
| Sign | Meaning |
|---|---|
| == | equal |
| != | not equal |
| < | less |
| > | greater |
| <= | less or equal |
| >= | greater or equal |
A pupil wrote a rule for a class quiz: a team goes through to the next round if its score is more than 20 and it made fewer than 3 mistakes. The program judged each team’s result as True or False, so there was no argument.
Programmers, testers and system designers judge conditions as True or False to control access.
Write one permission at school or home with two conditions, such as “age ≥ 10 and permission given”. Mark True or False for five different cases.
1x = 20 2print(x == 20, x != 20, x < 10, x >= 20)
True False False True
1a = 14 2print(a >= 10 and a <= 15, a < 10 or a > 18, not a == 14) 3print("kit" in "kitob", "Kit" in "kitob")
True False False True False
“True or False”: the teacher says 8 conditions (for x = 6: x > 3 and x < 5, x == 6 or x == 7, not x != 6 and so on). Groups raise cards with True or False; then it is checked in IDLE.