Puzzle 14 The Great Divide

Python Brain Teasers — by Miki Tebeka (23 / 40)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Identity Crisis | TOC | Where’s Waldo? 👉

div.py

​ ​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.

images/hline.png

This code will print: OK

images/hline.png

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.

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.