Shortcuts and number tools
🌍 In real life. A step counter on a phone adds to its total each time you walk: 1000 steps, then 250 more, then 250 more. It never writes "the total is now the old total plus 250"; it just adds. And at a shop, a price like 49.987 taka is rounded to 49.99 before it's shown.
Python has shortcuts for both: one for "add to what's already there", and ready-made tools for rounding and other number jobs.
The idea in one sentence: x += 3 is a short way to write x = x + 3, and Python has ready-made number tools like round, abs, max, min and the math module.
Its words:
- augmented assignment:
+=,-=,*=,/=,//=,%=and**=, each one "do this to the box's own value" - built-in function: a tool that's always there, like
round()ormax() - module: a toolbox you open with
import, likemath
Step by step, for score += 5:
- Python reads the old value in
score. - It adds 5.
- It puts the result back into
score.
score = 0
score += 5
score += 5
print(score)
lives = 3
lives -= 1
print(lives)Python has built-in helpers for numbers:
round(x)rounds to the nearest whole number, andround(x, 2)keeps 2 decimal placesabs(x)gives the distance from 0, which is never negativemax(...)andmin(...)pick the biggest and the smallest
print(round(3.7))
print(round(3.14159, 2))
print(abs(-8))
print(max(4, 9, 2))
print(min(4, 9, 2))For more maths, import math opens Python's maths toolbox. You use its tools with a dot, like math.sqrt(16). (Chapter 19 explains how import works.)
import math
print(math.sqrt(16))
print(math.pi)
print(math.floor(4.8))
print(math.ceil(4.2))One small surprise: round(2.5) gives 2, but round(3.5) gives 4. When a number is exactly halfway, Python rounds to the nearest even number.
print(round(2.5), round(3.5))Comparing decimals. Decimals are stored in binary (Lesson 3.1), so 0.1 + 0.2 == 0.3 is False: the sum is really 0.30000000000000004. Don't test decimals with ==. Round both sides to the places you care about, or use math.isclose(a, b), which says whether two numbers are equal apart from a tiny difference.
import math
print(0.1 + 0.2 == 0.3)
print(round(0.1 + 0.2, 2) == 0.3)
print(math.isclose(0.1 + 0.2, 0.3))Exact money: Decimal. For money, "nearly right" isn't good enough: add 0.1 taka ten times with floats and you get 0.9999999999999999. The decimal module keeps decimals exactly as you write them. Make a Decimal from a string, Decimal("0.1"), and the sums come out exact. Made from a float, Decimal(0.1) copies the float's tiny error. Most small programs are fine with floats and round; banks and shops use Decimal.
from decimal import Decimal
float_total = 0
exact_total = Decimal("0")
for _ in range(10):
float_total += 0.1
exact_total += Decimal("0.1")
print(float_total)
print(exact_total)
print(Decimal("19.99") * 3)Mistakes and edge cases.
- =+ instead of +=.
score =+ 5raises no error: it meansscore = +5, so the old score is thrown away andscorebecomes 5. - Adding to a box that doesn't exist yet.
steps += 250before anysteps = ...givesNameError: name 'steps' is not defined. - Forgetting the import.
math.sqrt(16)withoutimport mathgivesNameError: name 'math' is not defined. Did you forget to import 'math'? - Rounding a halfway decimal.
round(2.675, 2)is2.67, not 2.68: 2.675 is stored as a number a tiny bit smaller. - max() with nothing.
max()givesTypeError: max expected at least 1 argument, got 0.
Quiz
What does this print?
x = 10 x -= 4 print(x)What does this print?
x = 3 x *= 2 x += 1 print(x)What does this print?
print(abs(-12))What does this print?
print(round(7.456, 1))What does
import mathlet you use?- Extra maths tools such as math.sqrt
- A calculator window
- Faster + and -
This should print 15, but it prints 5. Which line has the mistake?
score = 10 score =+ 5 print(score)
Coding tasks
stepsholds 1000. Use+=to add 250 steps, twice. Then printsteps.priceholds 49.987. Makeroundedhold the price rounded to 2 decimal places.Two temperatures are given:
ais -7 andbis 3. Print the distance between them usingabs. It should not be negative.