Python for AIPython 3.10+ · Pydantic 2.12
Dashboard
0%
1
Curious builder0 XP earned · 300 to level 2
0 daysFinish a lesson to begin
Badge collection0 of 6 unlocked
34 small wins to finish your pathNext lesson →

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

Example
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.

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.

Example
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.

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.

Example
quantity = "2"
print(quantity + 1)

The quotes made quantity a string, and Python will not guess whether you meant maths or joining text.

Converting with int(), float() and str()

Example
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:

Example
print(int("two"))

/ vs // vs %

Operator10 and 4 giveUse it for
/2.5Ordinary division, always a float
//2Whole groups, such as full pages of results
%2What 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().
Watch out. 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")).
Try it yourself
  • 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 // 2 and 7 % 2, and check that 2 × 3 + 1 gives 7 back.
  • Try int("4.5"), then int(float("4.5")).
PreviousStrings

Every expert started right here.