What happens first
Multiplication happens before addition. Parentheses change that. Bitwise operators work on whole numbers.
- Predict 2 + 3 * 4 as 14, because * happens first
- Use parentheses to add first
- Use &, |, ^, ~, <<, and >> on whole numbers
On one line, * and / happen before + and -. 2 + 3 * 4 is 2 + 12, which is 14. Parentheses happen first: (2 + 3) * 4 is 5 * 4, which is 20. A classic slip is an average: a + b / 2 halves only b. You need (a + b) / 2.
Run each example to see what it prints. Running examples doesn't count toward progress.
print(2 + 3 * 4) print((2 + 3) * 4)
A separate family: bitwise operators. These work on the binary digits, the bits, of whole numbers. They are not and and or. bin(5) shows 5 in binary as 0b101, and bin(3) is 0b11, which lines up as 011.
& keeps a 1 only where both numbers have a 1: 101 & 011 is 001, which is 1. | keeps a 1 where either has one: 111, which is 7. ^ keeps a 1 where exactly one has it: 110, which is 6.
<< shifts the bits left and >> shifts them right. n << 1 is n times 2, and n >> 1 is n // 2. ~n flips every bit, which for a whole number gives -(n + 1), so ~5 is -6. Bitwise operators come after + and - in the order, so use parentheses when you mix them.
print(bin(5)) print(bin(3)) print(5 & 3) print(5 | 3) print(5 ^ 3) print(~5) print(1 << 2) print(8 >> 1)
Where bits are used. One whole number can hold several yes-or-no settings, one per bit. With gift wrap as 1 and express as 4, the number 5 (101) means both are on. options & 4 is 4 when the express bit is on and 0 when it is off. options | 1 switches gift wrap on, and leaves it on if it already was, which options + 1 would not do.
- * and / happen before + and -. Parentheses happen first, so an average needs them.
- & | and ^ combine bits of whole numbers. They are not and, or, or +.
- bin(n) shows the bits. << 1 doubles, >> 1 is // 2, and ~n is -(n + 1). Next module: choosing what to run with if.