Puzzle 14 The Great Divide
Python Brain Teasers — by Miki Tebeka (23 / 40)
👈 Identity Crisis | TOC | Where’s Waldo? 👉
def div(a, b):
return a / b
if div(1, 2) > 0 or div(1, 0) > 0:
print('OK')
else:
print('oopsie')
Guess the Output
IMPORTANT
Try to guess what the output is before moving to the next page.
This code will print: OK
You probably expected this code to raise ZeroDivisionErro due to div(1, 0).
If you call div(1, 0) by itself, you will see the exception. Yet the logic operators in Python, and and or, are short-circuit operators.
Here’s what the documentation says on and:
This is a short-circuit operator, so it only evaluates the second argument if the first one is false.
In contrast, all arguments to a function call are evaluated before calling the function. This means you can’t write your own my_and function that will behave like the built-in and.