Skip to content

Commit 7feb730

Browse files
blazewiczdpgeorge
authored andcommitted
tests/basics: Add tests for arithmetic operators precedence.
1 parent 91a385d commit 7feb730

1 file changed

Lines changed: 43 additions & 0 deletions

File tree

tests/basics/op_precedence.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
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)

0 commit comments

Comments
 (0)