Python 3D Academyবাংলা

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() or max()
  • module: a toolbox you open with import, like math

Step by step, for score += 5:

  1. Python reads the old value in score.
  2. It adds 5.
  3. 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, and round(x, 2) keeps 2 decimal places
  • abs(x) gives the distance from 0, which is never negative
  • max(...) and min(...) 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))
sqrt is the square root, floor rounds down and ceil rounds up.

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 =+ 5 raises no error: it means score = +5, so the old score is thrown away and score becomes 5.
  • Adding to a box that doesn't exist yet. steps += 250 before any steps = ... gives NameError: name 'steps' is not defined.
  • Forgetting the import. math.sqrt(16) without import math gives NameError: name 'math' is not defined. Did you forget to import 'math'?
  • Rounding a halfway decimal. round(2.675, 2) is 2.67, not 2.68: 2.675 is stored as a number a tiny bit smaller.
  • max() with nothing. max() gives TypeError: max expected at least 1 argument, got 0.

Quiz

  1. What does this print?

    x = 10
    x -= 4
    print(x)
  2. What does this print?

    x = 3
    x *= 2
    x += 1
    print(x)
  3. What does this print?

    print(abs(-12))
  4. What does this print?

    print(round(7.456, 1))
  5. What does import math let you use?

    • Extra maths tools such as math.sqrt
    • A calculator window
    • Faster + and -
  6. This should print 15, but it prints 5. Which line has the mistake?

    score = 10
    score =+ 5
    print(score)

Coding tasks

  1. steps holds 1000. Use += to add 250 steps, twice. Then print steps.

  2. price holds 49.987. Make rounded hold the price rounded to 2 decimal places.

  3. Two temperatures are given: a is -7 and b is 3. Print the distance between them using abs. It should not be negative.