So, now that we know how Boolean short-circuiting works, we can explain how `f` works.
Let's break the explanation down into two cases:
π x % 2 == 1
π x % 2 == 0
π x % 2 == 1
If x % 2 is 1, then the function body simplifies to
(1 and "odd") or "even"
π
"odd" or "even"
At this point, because of short-circuiting, `or` sees a Truthy value on the left, and simply returns `"odd"`.
π x % 2 == 0
If x % 2 is 0, then the function body simplifies to
(0 and "odd") or "even"
π
0 or "even"
At this point, the left of `or` is Falsy, so it evaluates the right operand, which is `"even"`, and returns it!
That's it, that's how the function `f` works to determine if numbers are odd or even!
Did you learn from this π§΅?
This is what I love to do: break down Python π and explain it to you in a simple manner!
Follow @mathsppblog for more content like this π
See you around π
TL;DR:
π `and` has higher precedence than `or`;
π Boolean short-circuiting means Python will only evaluate the operands it needs;
π we also use the truthy/falsy values of 1, 0, "odd", and "even".
Found a weird piece of Python code?
DM it to me! I'll explain it in a β‘π§΅
β
β’ β’ β’
Missing some Tweet in this thread? You can try to
force a refresh