Fixing Types

Everything out of a file is text, and text sorts and adds in the wrong way.

Text that looks like a number

The bug is quiet: "9" is greater than "10" as text, because comparison goes character by character. Convert on the way in, not at the point of confusion.

print("9" > "10")
print(int("9") > int("10"))
print("9" + "10")
print(int("9") + int("10"))

Converting safely

int() raises on anything that is not a whole number in text. Deciding what a bad value should become is part of cleaning, not an afterthought.

def to_int(text, default=0):
    try:
        return int(text)
    except ValueError:
        return default

print(to_int("92"), to_int(""), to_int("n/a", -1))

Exercise

Try It Yourself

Write to_score(text) that returns the number in text, or 0 when it is not a number at all.

Press Run to see output

Check Your Understanding