2

When I evaluate the following expression:

1 or (1/0) and 1

What are the rules (precedence, short-circuit evaluation etc) are followed to get the answer

Craig Burgler
  • 1,749
  • 10
  • 19
Omar Khan
  • 412
  • 2
  • 12
  • This question has NOT been already asked. The question that refers to the priority of NOT AND & OR in python does not address the short circuit evaluation taking place here. – Omar Khan Sep 07 '16 at 14:48

2 Answers2

2

b or anything_else is defined to return b if b is true-ish, without evaluating anything_else. Since your first 1 is true-ish, your 1/0 never gets evaluated, hence no error. By "true-ish" I mean any value that Python considers true, not only the True boolean value. Try your expression with True or [2] in place of the first 1 to see what I mean.

D-Von
  • 416
  • 2
  • 5
1

Python short-circuit evaluates. In your example, the expression

1 or (1/0) and 1

finishes evaluation at the first 1 and returns True.

A more minimal example serves to illustrate Python's short-circuit evaluation. Consider the expression:

(1/0) or 1

This raises a ZeroDivisionError exception upon evaluation of (1/0). But the expression:

1 or (1/0)

short-circuit evaluates to True. No exception is raised since the sub-expression (1/0) never gets evaluated.

Craig Burgler
  • 1,749
  • 10
  • 19