Numbers and type conversion
int and float are Python's number types, for whole numbers and for numbers with a decimal point, and int(), float() and str() convert between them and text.
Last updated: 30 Sep, 2026 · Python 3.14
Models are paid for by the amount of text they read and write, so even a program about strings does sums.
Doing arithmetic
price = 499
quantity = 2
print(price * quantity)
print(10 / 4)
print(10 // 4)
print(10 % 4)998 2.5 2 2
* 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.
Estimating a model's cost
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))0.1851 0.19
round(cost, 2) keeps two digits after the point, so 0.1851 becomes 0.19. Round a cost before showing it to a person.
Adding to 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)Traceback (most recent call last):
File "main.py", line 2, in <module>
print(quantity + 1)
TypeError: can only concatenate str (not "int") to strThe quotes made quantity a string, and Python will not guess whether you meant maths or joining text.
Converting with int(), float() and str()
quantity = "2"
print(int(quantity) + 1)
print(float("0.15") * 2)
print("Total: " + str(998))3 0.3 Total: 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"))Traceback (most recent call last):
File "main.py", line 1, in <module>
print(int("two"))
ValueError: invalid literal for int() with base 10: 'two'/ vs // vs %
| Operator | 10 and 4 give | Use it for |
|---|---|---|
/ | 2.5 | Ordinary division, always a float |
// | 2 | Whole groups, such as full pages of results |
% | 2 | What is left over |
Where numbers show up in AI code
- Counting tokens and estimating what a run costs.
- Settings such as a temperature of 0.2 or a limit of 50 tokens.
- Scores a model gives, which often arrive as text and need
float().
int("4.5") fails even though 4.5 is a number. int only reads whole numbers from text; use float first, as in int(float("4.5")).Related
- Previous: Strings
- Next: if, elif and else
- Reference: Numeric types in the Python docs
- 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")).
Every expert started right here.