Numbers and names
Part of the free LogicWiz Python course, Module 1: Start coding. The examples and practice run in the app.
Aarav says 2 + 3 * 4 is 14. Meher says 20. Python agrees with Aarav, every time. Why?
You'll learn to
- Use + - * / // % ** like a calculator
- Predict which operator goes first (precedence), including right-to-left `**`
- Store values in names and update them
- Read `x = x + 1` the way Python does
Learn
Python as a calculator
print(7 + 3)
print(7 - 3)
print(7 * 3)
print(7 / 2)
print(7 // 2)
print(7 % 2)
print(2 ** 10)
/ always gives a decimal (3.5). // divides and drops the fraction (3). % gives the remainder (1). ** is power: 2 to the 10th is 1024.
The seven arithmetic operators
| Operator | Meaning, example |
|---|---|
| + - | add, subtract, multiply: 6 4 is 24 |
| / | divide, always a float: 8 / 2 is 4.0 |
| // | floor division, whole part: 17 // 5 is 3 |
| % | remainder (modulus): 17 % 5 is 2 |
| power: 3 2 is 9 |
Who goes first: precedence
Python follows a fixed order, like BODMAS:
- Brackets
( ) **power, and it goes right to left. It even beats a minus sign in front:-2 ** 2is-(2 ** 2)= -4 (a board-exam favourite)* / // %, left to right+ -, left to right
So 2 + 3 * 4 is 2 + 12 = 14. 2 ** 3 ** 2 is 2 ** 9 = 512, not 8 ** 2. When in doubt, add brackets: they cost nothing and make code clear.
Precedence in action
print(2 + 3 * 4)
print((2 + 3) * 4)
print(10 - 4 - 3)
print(2 ** 3 ** 2)
print((2 ** 3) ** 2)
print(-2 ** 2)
10 - 4 - 3 goes left to right (3). ** goes right to left. -2 ** 2 is -(2 ** 2) = -4, because ** binds tighter than the minus sign.
Names point to values
price = 15 does not mean price equals 15 like in maths. It means make the name price point to the value 15.
Think of a name as a sticky label on a value. Later you can move the label: price = 18 peels it off 15 and sticks it on 18.
A name must exist before you use it. Using a name you never set gives NameError.
Watch the labels move
samosa = 15
chai = 10
total = samosa * 2 + chai
print(total)
samosa = 18
print(total)
total = total + 5
print(total)
Changing samosa later did not change total. total got the value 40 when its line ran, and it keeps 40 until you assign it again.
x = x + 1 is not a broken equation. Python works out the right side first (take x, add 1), then points x at the result. Shortcut: x += 1. Same for -=, *=, //=. And you can set two names at once: a, b = 5, 10, or swap them with a, b = b, a.
CBSE loves "Evaluate: 2 ** 3 ** 2" and "Evaluate: 15 // 4 * 2 % 3". Apply the order rule one step at a time and write each step. Also expected: augmented assignment (+=) and multiple assignment (a, b = b, a).
In one line
// drops the fraction, % gives the remainder, ** runs first and right to left; = points a name at a value, it is not an equation.