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
Would you like me to teach you how to write Python π code that is more elegant, more effective, and more expressive than what you have been writing until now... for free?
I am looking to teach Python to people who want to master Python to the best of their abilities.
Do you? If you do, then I know I can help you improve your skills.
How do I know that?
My book has over 10,000 readers, and all of them have one thing in common: they are humans.
Python has dozens of built-ins, and all of them have multiple usage patterns. No human knows all of them by heart, but my research bundled them up nicely in a book for you to reference and learn from.