Search⌘ K
AI Features

Puzzle 14: Explanation

Explore how Python's short-circuit operators and or affect function calls and code evaluation. Understand why exceptions like ZeroDivisionError may not occur in certain expressions, and learn to apply this knowledge when writing efficient conditional code.

We'll cover the following...

Let’s try it!

Try running the code below to verify the result:

Python 3.8
def div(a, b):
return a / b
if div(1, 2) > 0 or div(1, 0) > 0:
print('OK')
else:
print('oopsie')

Explanation

Most people expect this code to raise ZeroDivisionError due to div(1, 0). If we call div(1, 0) by itself, we’ll see that exception. Still, the logic ...