File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ # see https://docs.python.org/3/reference/expressions.html#operator-precedence
2+
3+ # '|' is the least binding numeric operator
4+
5+ # '^'
6+ # OK: 1 | (2 ^ 3) = 1 | 1 = 1
7+ # BAD: (1 | 2) ^ 3 = 3 ^ 3 = 0
8+ print (1 | 2 ^ 3 )
9+
10+ # '&'
11+ # OK: 3 ^ (2 & 1) = 3 ^ 0 = 3
12+ # BAD: (3 ^ 2) & 1 = 1 & 1 = 1
13+ print (3 ^ 2 & 1 )
14+
15+ # '<<', '>>'
16+ # OK: 2 & (3 << 1) = 2 & 6 = 2
17+ # BAD: (2 & 3) << 1 = 2 << 1 = 4
18+ print (2 & 3 << 1 )
19+ # OK: 6 & (4 >> 1) = 6 & 2 = 2
20+ # BAD: (6 & 4) >> 1 = 2 >> 1 = 1
21+ print (6 & 4 >> 1 )
22+
23+ # '+', '-'
24+ # OK: 1 << (1 + 1) = 1 << 2 = 4
25+ # BAD: (1 << 1) + 1 = 2 + 1 = 3
26+ print (1 << 1 + 1 )
27+
28+ # '*', '/', '//', '%'
29+ # OK: 2 + (2 * 2) = 2 + 4 = 6
30+ # BAD: (2 + 2) * 2 = 4 * 2 = 8
31+ print (2 + 2 * 2 )
32+
33+ # '+x', '-x', '~x'
34+
35+ # '**'
36+ # OK: -(2**2) = -4
37+ # BAD: (-2)**2 = 4
38+ print (- 2 ** 2 )
39+ # OK: 2**(-1) = 0.5
40+ print (2 ** - 1 )
41+
42+ # (expr...)
43+ print ((2 + 2 ) * 2 )
You can’t perform that action at this time.
0 commit comments