B Operators
Every operator
| Operator | Means | Works on |
|---|---|---|
a + b |
add; join text; join lists | numbers, quantities, str,
lists |
a - b |
subtract | numbers, quantities, pointers |
-a |
negate | numbers, quantities |
a * b |
multiply | numbers; a quantity by a number |
a / b |
divide, always giving a
float |
numbers, quantities |
a // b |
divide and round down | numbers |
a % b & remainder of
//, with the sign of b & numbers |
remainder of //, with the
sign of b |
numbers |
a ** b |
power | numbers |
a & b |
bit and | whole numbers |
a | b |
bit or | whole numbers |
a ^ b |
bit exclusive or | whole numbers |
~a |
every bit turned over | whole numbers |
a << n,
a >> n |
shift left, shift right | whole numbers |
a == b,
a != b |
equal, not equal, by contents | values of one type |
a < b, <=,
>, >= |
order; they chain:
0 <= i < n |
numbers, quantities, str |
x in xs,
x not in xs |
is it there? | lists, text, dict keys |
x is none,
x is not none |
is it nothing? | T or none |
a and b, a or b,
not a |
logic, asking the right side only when needed | bool |
xs[i] |
item i, from 0 |
lists, text, dicts, pointers |
x.name |
a field, a method, a module’s name, a unit change | |
f(a, b) |
a call | functions, classes, enum cases |
Which goes first
From the loosest to the tightest:
| Operators | |
|---|---|
or |
loosest |
and |
|
not |
|
== != < <= > >= in not in is is not |
comparisons, which chain |
| |
|
^ |
|
& |
|
<< >> |
|
+ - |
|
* / // % & |
|
-x ~x |
|
** |
tightest; and it groups to the right |
The bit operators bind tighter than the comparisons, as in Python and
unlike C. So this test means what it looks as if it means,
(flags & MASK) == 0:
let ready = flags & MASK == 0The = forms
Every operator on two numbers has an = form, which
updates a var, a field or an item:
+= -= *= /= //= %= **= &= |= ^= <<= >>=
x += y means x = x + y, with x
read first. On a sized number the result is checked as it is stored, so
count += 1 on a u8 of 255 is an
OverflowError. /= is refused on a whole
number, because / gives a float. A list takes
+= to add another list to its end.
What raises
| When | Raises |
|---|---|
| a whole-number answer does not fit in 64 bits | OverflowError |
// or % by zero,
or / by zero & ZeroDivisionError |
ZeroDivisionError |
| a whole number to a negative power | ValueError |
| a shift by less than 0 or more than 63 | ValueError |
| a shift left that loses bits | OverflowError |
xs[i] outside the list or
text |
IndexError |
d[key] of a key that is not
there |
KeyError |