Add, subtract, multiply, divide
Arithmetic operators compute a new number from values you have stored.
- Add, subtract, and multiply stored numbers
- See that / gives a decimal, while // and % split a whole number
- Raise a number to a power with **
Programs compute: a cart total, the change from a payment, how many boxes an order needs. +, -, and * compute a new number. Write each operation on its own line for now. price + shipping adds the two stored values. The names themselves do not change unless you store the result.
Run each example to see what it prints. Running examples doesn't count toward progress.
price = 20 shipping = 5 items = 3 print(price + shipping) print(price - shipping) print(items * price)
/ always gives a decimal, so 8 / 2 prints 4.0. // divides and rounds down to a whole number. % is the remainder. Together they split a quantity: how many full boxes, and how many items left over. ** raises to a power: 2 ** 3 is 2 times 2 times 2.
+ on text sticks the text together. "12" + "30" is the text 1230. int("12") + int("30") is the number 42. That is why the previous module converts text before you do arithmetic.
print(8 / 2) print(8 // 3) print(8 % 3) print(2 ** 3) print("12" + "30") print(int("12") + int("30"))
Mistakes to avoid. Using / when you need a count gives a decimal like 3.4. Adding numbers that are still text sticks them together instead of adding. And decimals can show a tiny error: 0.1 + 0.2 prints 0.30000000000000004, because decimals are stored in binary. That is normal, not a bug in your program.
- + - and * compute a new number. Store the result if you need it later.
- / gives a decimal. // rounds down to a whole number, and % is the remainder. ** is a power.
- + on text sticks the text together. Convert with int() or float() before you add numbers that arrived as text. Next: comparing two values.