Numbers: int, float and converting text
Models are paid for by the amount of text they read and write, so even a program about text does sums. Here is the arithmetic, and the mistake everyone makes.
price = 499
quantity = 2
print(price * quantity)
print(10 / 4)
print(10 // 4)
print(10 % 4)* multiplies. / always gives a float, even when the answer is whole. // divides and drops the part after the decimal point, and % gives what is left over.
A cost estimate
Model providers count text in tokens, pieces of words, and charge a price per thousand or per million of them.
tokens = 1234
price_per_1000 = 0.15
cost = tokens / 1000 * price_per_1000
print(cost)
print(round(cost, 2))round(cost, 2) keeps two digits after the point, so 0.1851 becomes 0.19. Round a cost before showing it to a person; nobody is billed in ten-thousandths.
Text that looks like a number
A number that arrives from a file, a form or a model often arrives as text. Adding to it fails.
quantity = "2"
print(quantity + 1)The quotes made quantity a string, and Python will not guess whether you meant maths or joining text. Convert it first.
quantity = "2"
print(int(quantity) + 1)
print(float("0.15") * 2)
print("Total: " + str(998))int, float and str each turn a value into that type. Text that is not a number cannot become one, and that is a different error:
print(int("two"))- Work out the cost of 250,000 tokens at 2.5 per thousand. Write the number as
250_000; underscores in numbers are allowed and ignored. - Print
7 // 2and7 % 2, and check that 2 × 3 + 1 gives 7 back. - Try
int("4.5"), thenint(float("4.5")).
This is what real progress feels like.