All programming languages that evaluate expressions involving various mathematical and other operations need to perform the operations in a defined order. This is necessary so that the values of expressions are not ambiguous.
Operator precedence charts specify the order in which operations are performed. See 5.15. Operator precedence. In that chart the operators are listed from lowest to highest precedence. Accordingly, the operations at the bottom are performed first. Note that the
== operation is performed before the
or operation. Therefore, this ...
if type(x) == int or float:
... is equivalent to this ...
if (type(x) == int) or float:
x is not an
int, the portion of the expression to the right of the
or is used, by the interpreter, as the value of the entire expression. The resulting value,
float, when considered as a condition, corresponds to a
True result, so the expression is, in effect,
True. That is not acceptable, because it causes the
if block to execute regardless of the value of
This works correctly, because it compares
int and then, if necessary, compares it to
if type(x) == int or type(x) == float:
Note, from the line at the bottom of the chart, that parentheses can be used to exert some control on the order of operations. However, in the current case, merely inserting parentheses will not correct the problem.
In some operator precedence charts, the order is listed with highest precedence at the top, so always read explanatory information that is provided with the chart.