JuniorCodeCommonNot answered yet
What do these or / and expressions print?
Predict all three lines.
print([] or "default") # (1)
print(0 or 5 or 10) # (2)
print("a" and "b" and "") # (3)
Determine the output and explain.
(1) default — or returns the first truthy operand (an empty list is falsy). (2) 5 — the first truthy value. (3) '' — and returns the first falsy operand, or the last if all are truthy. or/and return one of the operands, not a bool — the basis of x = val or default.
- ✗Believing
or/andalways return a boolean - ✗Thinking they always return the first operand regardless of truthiness
- ✗Not knowing the
x = val or defaultidiom relies on this
- →Why does short-circuit evaluation return an operand rather than a bool?
- →What is the risk of
x = val or defaultwhenvalcan be0or''?