Sub topic 17
Checking your work with Python
This chapter assumes you can apply the full order of operations by hand, including negative bases, fractions, and exponents. It also assumes you can run a short Python script, in a file or in the interactive prompt. Python is a second opinion. It doesn't replace the hand method.
Why use code as a checker
A calculator gives you one number and little else. A short program gives you a record you can rerun and compare against each hand step. It can also tell you when your hand answer and the machine disagree.
Python is a good checker for this topic because its precedence rules match the written convention in almost every case. The rest of this chapter covers the places where they differ. Those places are where beginners get misled.
How Python orders operations
Python evaluates arithmetic in this order, from first to last:
| Rank | Operators | Notes |
|---|---|---|
| 1 | `( )` | Innermost parentheses first |
| 2 | `**` | Right to left: `2 ** 3 ** 2` is `2 ** (3 ** 2)` |
| 3 | unary `-x`, `+x` | Binds more loosely than `**` on its left |
| 4 | `*`, `/`, `//`, `%` | Same rank, left to right |
| 5 | `+`, `-` | Same rank, left to right |
This table is the same hierarchy you use by hand. It explains why -3 ** 2 gives -9. The ** operator applies to 3 first, and the minus sign applies afterwards.
print(2 + 3 * 4 ** 2) # 50
print(-3 ** 2) # -9
print((-3) ** 2) # 9
print(24 / 4 * 3) # 18.0
print(10 - 4 + 3) # 9
print(2 ** 3 ** 2) # 512
print((2 ** 3) ** 2) # 64A minus sign on the right of ** is fine. 2 ** -2 is 0.25, because Python reads the exponent as -2.
Exact answers with Fraction
Ordinary Python division returns a float, which is a binary approximation. Many fractions can't be stored exactly as floats. That makes floats a poor check for a hand answer written as a fraction.
from fractions import Fraction
print(0.1 + 0.2 == 0.3) # False
print(Fraction(1, 10) + Fraction(2, 10) == Fraction(3, 10)) # True
print(Fraction(1, 3) == 1 / 3) # FalseFraction keeps the numerator and denominator as integers and reduces the result. It follows the same precedence rules as other numbers.
from fractions import Fraction
result = Fraction(1, 2) + Fraction(3, 4) * Fraction(2, 3) ** 2
print(result) # 5/6
print(Fraction(2, 3) ** -2) # 9/4
print(Fraction(-2, 3) ** -2) # 9/4A hand trace for the first line: (2/3)**2 = 4/9, then 3/4 * 4/9 = 1/3, then 1/2 + 1/3 = 5/6.
Build every fraction with Fraction(a, b). If you write 1/2 + 3/4 in Python, each piece becomes a float before Fraction sees it. Mixing a Fraction with a float also returns a float, so one stray / can turn an exact check into an approximate one.
A comparison helper
Write a small function that compares your hand answer to the computed one and says which it is. You can reuse it for every problem.
from fractions import Fraction
def check(label, hand, computed):
status = "ok" if hand == computed else "MISMATCH"
print(f"{status:<9} {label}: hand={hand}, python={computed}")
check("2 + 3 * 4 ** 2", 50, 2 + 3 * 4 ** 2)
check("-3 ** 2", -9, -3 ** 2)
check("10 - 4 + 3", 9, 10 - 4 + 3)
check("1/2 + 3/4 * (2/3)**2", Fraction(5, 6),
Fraction(1, 2) + Fraction(3, 4) * Fraction(2, 3) ** 2)
check("(3 + 5) / (2 + 2)", 2, (3 + 5) / (2 + 2))
check("24 / 4 * 3, wrong hand answer", 2, 24 / 4 * 3)The output is:
ok 2 + 3 * 4 ** 2: hand=50, python=50
ok -3 ** 2: hand=-9, python=-9
ok 10 - 4 + 3: hand=9, python=9
ok 1/2 + 3/4 * (2/3)**2: hand=5/6, python=5/6
ok (3 + 5) / (2 + 2): hand=2, python=2.0
MISMATCH 24 / 4 * 3, wrong hand answer: hand=2, python=18.0The last line is a deliberate error. Someone who did 4 * 3 first and then 24 / 12 would get 2. Python reports a mismatch, and you then trace both versions to find the step where they diverge. Note that 2 == 2.0 is True in Python, so an integer hand answer matches a float result.
Typing a fraction bar
A written fraction bar groups the numerator and the denominator. Python has no bar, so you supply the grouping with parentheses.
print((3 + 5) / (2 + 2)) # 2.0
print(3 + 5 / 2 + 2) # 7.5The second line is what you get if you type the fraction without grouping. Only the 5 is divided by 2. This is the most common translation error when checking fraction work.
The workflow
Check in this order. Work the problem by hand first, so the check tests your method and not your ability to copy a result.
When results differ, don't assume Python is right. The translation may be wrong, for example a missing pair of parentheses. Print the intermediate values to find the first step where hand and code disagree.
from fractions import Fraction
step1 = Fraction(2, 3) ** 2
step2 = Fraction(3, 4) * step1
step3 = Fraction(1, 2) + step2
print(step1, step2, step3) # 4/9 1/3 5/6Where Python and written math differ
^is not an exponent. In Python,^is bitwise XOR.2 ^ 3is1, not8. Use**.- No implicit multiplication.
8 / 2(2 + 2)raises aTypeError, because Python reads2(...)as a function call. You must write*yourself, and in doing so you choose a reading:8 / 2 * (2 + 2)is16.0, while8 / (2 * (2 + 2))is1.0. Python can't tell you which one the author meant. /always returns a float.6 / 3is2.0. Use//for floor division, which rounds toward negative infinity.-7 // 2is-4, not-3. Don't use//to model ordinary fraction division.- Zero to a negative power fails.
0 ** -1raisesZeroDivisionError, as doesFraction(0) ** -1. Hand work should reach the same conclusion: the expression is undefined. - Integer powers are exact.
2 ** 100is computed exactly with integers. Float results such as2 ** -2are approximate in general, though0.25happens to be exact.
Using code to settle a doubt
Code is useful for testing a rule you aren't sure of. If you wonder whether -2 ** 2 and (-2) ** 2 differ, run both. If you wonder whether subtraction is left to right, compare 10 - 4 + 3 with 10 - (4 + 3). One line of output settles the question, and you can then work out why by hand.
Exercise
Without running it first, predict what Python prints for -2 ** 2, (-2) ** 2, and 2 ** -1. Then say why 7 - 1 / 2 * 3 is not the Python version of "(7 − 1) over (2 · 3)", and give the correct expression and its value.
Show answer
-2 ** 2 prints -4, because ** is applied before the minus sign. (-2) ** 2 prints 4, because the parentheses make -2 the base. 2 ** -1 prints 0.5. The expression 7 - 1 / 2 * 3 evaluates 1 / 2 * 3 first, which is 1.5, and gives 5.5. The fraction bar groups the top and bottom, so write (7 - 1) / (2 * 3), which gives 1.0.
Exercise
Write Python that uses Fraction to check the hand result (1/2 - 1/3) ** -2 = 36, and say what the printed value is.
Show answer
from fractions import Fraction then print((Fraction(1, 2) - Fraction(1, 3)) ** -2). The subtraction gives 1/6, and a negative exponent takes the reciprocal, so the result is 6 ** 2 = 36. Python prints 36.