Comparisons and logic
Picture a ticket checker at the door of a cinema showing an 18+ film. The checker asks questions answered with "yes" or "no": do you have a ticket, are you 18 yet. You get in only when both answers are "yes".
A program constantly needs the same kind of answers: whether a user is an adult, whether a number falls within a range. Such an answer comes from a comparison, and its result has type bool:
age = 20
adult = age >= 18
teen = 13 <= age <= 19
print(adult, teen) # True False
print(age == 20, age != 20) # True FalseLet's go through the program line by line:
adult = age >= 18puts the answer to "is twenty at least eighteen?" intoadult:True.teen = 13 <= age <= 19checks whetheragefalls within the range from 13 to 19. Twenty does not, soteenisFalse.- The last line prints
True False:ageis20, so "is not 20" is false.
Comparisons
There are six comparison operators:
==means equal;!=means not equal;<and<=mean less than, less than or equal;>and>=mean greater than, greater than or equal.
The double sign == checks equality, and a single = assigns a value. An int and a float compare by value: 1 == 1.0 gives True. A string never equals a number: "5" == 5 gives False.
Comparisons can be chained, as in math. The chained comparison 13 <= age <= 19 means "13 <= age, and also age <= 19". Comparisons run after arithmetic: n % 2 == 0 means (n % 2) == 0.
and, or and not
Logical operators join conditions, the way the checker joins the questions. There are three of them.
and
a and b holds when both operands hold. That is how the checker lets you in: you have a ticket, and you are 18.
or
a or b holds when at least one operand holds. That is how the cashier gives a discount: the viewer is a student or a retiree.
not
not a turns True into False and back. not runs first, then and, and or comes last.
Short circuit
Once the checker sees there is no ticket, they no longer ask about age: the answer is clear. Python does the same. and and or evaluate the left operand first, and if it already settles the answer, the right one is not evaluated at all.
For and that is a false left operand, for or a true one. This rule is called short-circuit evaluation:
def is_positive(n):
print("check", n, end=" ")
return n > 0
print(is_positive(-1) and is_positive(5)) # check -1 False
print(is_positive(5) or is_positive(-1)) # check 5 TrueLet's see what got printed:
is_positive(-1)printscheck -1and returnsFalse.- The left operand of
andis false, sois_positive(5)is not called, andprintoutputsFalse. - In the second line,
is_positive(5)returnsTrue, andorno longer callsis_positive(-1).
In each line the function was called once: the right operand was not needed.
What and and or return
Here the checker analogy ends. The checker answers only "yes" or "no", but and and or in Python return one of their operands.
An operand of and and or need not be a bool. Then zero and the empty string "" count as false, and other numbers and non-empty strings count as true. The result is the operand where evaluation stopped:
print(0 or 7, "" or "guest", 5 or 7) # 7 guest 5
print(0 and 7, 5 and 7) # 0 7
print(not 5, not "") # False TrueThe rules are:
orreturns the first true operand or, if there is none, the last one;andreturns the first false operand or, if all are true, the last one;notalways returnsTrueorFalse.
That is why "" or "guest" gives guest: this is how a default value replaces an empty string. Interviewers like to ask this: "What does 0 or 7 return?" The right answer is 7, not True.
Common mistake
The check "the answer is 1 or 2" is written the way it is said:
answer = 3
is_valid = answer == 1 or 2 # ✗
print(is_valid) # 2Python reports no error. The expression reads as (answer == 1) or 2: the left side gave False, and or returned the right operand 2. Each side needs its own comparison: answer == 1 or answer == 2 gives False.
Key points
- A comparison gives a
bool;==checks equality, and=assigns. andandordo not evaluate the right operand if the left one settles the answer.orreturns the first true operand,andthe first false one; if there is none, both return the last one.
Subscribe to take the course
The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.