Search⌘ K
AI Features

Puzzle 14: Explanation

Explore the behavior of Python's short-circuit operators and how they differ from regular function calls. Understand why expressions with and and or can prevent errors like ZeroDivisionError and learn how to apply this to efficiently control code execution, such as conditionally loading data only when needed.

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 because of div(1, 0). If we call div(1, 0) by itself, it does raise that ...