Python int() Function: Syntax and 6 Examples

If you have a numeric string or a float in Python and you want a whole number, the Python int function is the quickest way to get it. It takes "42" or 7.9 and gives you back an int for math.

print(int("42") + int(7.9))
# 49

In this tutorial, I’ll cover the syntax plus six examples: strings, floats, binary and hex text, CSV data, try/except and custom objects. Every output comes from Python 3.12.5 in VS Code.

Python int() Syntax

int(number=0, /)
int(string, /, base=10)
ParameterRequiredDefaultDescription
numberNo0A float, bool or number-like object
stringNononeText (str or bytes) holding a whole number
baseNo100 or 2-36, strings only

Return value: a new int, or 0 with no argument. Floats are cut toward zero, and invalid text raises ValueError.

Note: digit underscores work since Python 3.6. For the reverse, see how to convert an integer to a string in Python.

When to Use int() in Python

  • Reading numbers a user types, which arrive as strings
  • Converting CSV or Excel quantities to numbers
  • Dropping the decimal part of a float
  • Reading binary or hex text like "ff"

You’ll often pair it with the Python input() function.

Example 1: Convert a String to an Integer with int()

Let me start with strings, the most common job:

print(int("42"))
print(int("  -17\n"))
print(int("+250"))
print(int("1_000_000"))
print(int(b"64"))
print(int())

Output:

42
-17
250
1000000
64
0
Python int function converting strings with spaces, signs, underscores and bytes to integers in VS Code
Spaces, signs and underscores work.

How does this work? int() stripped the spaces and newline around -17, kept the sign, dropped the underscores and read bytes too. With no argument, you get 0.

For more ways, read converting a string to an integer in Python.

Example 2: Does int() Round or Truncate a Float in Python?

Here I’ll compare int() with round() on a few prices:

for price in [19.99, 7.5, -7.5, -0.9]:
    print(price, "->", int(price), round(price))

Output:

19.99 -> 19 20
7.5 -> 7 8
-7.5 -> -7 -8
-0.9 -> 0 -1
Python int truncating floats toward zero compared with round in VS Code
int() cuts toward zero; round() rounds.

How does this work? int(19.99) gave 19 and int(-0.9) gave 0, because int() just drops the decimals. round(7.5) gave 8.

Pro Tip: need a different rule? See the Python round() function or other float to int methods.

Example 3: Convert Binary, Octal and Hex Strings with base

The base argument reads text in any base from 2 to 36:

print(int("1010", 2))
print(int("ff", 16), int("FF", 16))
print(int("0o755", 8))
print(int("0x1F", 0), int("0b11", 0), int("42", 0))
print(int("z", 36))

Output:

10
255 255
493
31 3 42
35
Python int with base 2, 16, 8, 0 and 36 converting binary, hex and octal strings in VS Code
Base 0 reads the prefix.

How does this work? "1010" in base 2 is 10, and "ff" is 255 in either case. Base 0 read each prefix, and in base 36, z equals 35.

More detail: converting a binary string to an int and converting a hex string to an integer.

Example 4: Convert a List of Strings to Integers in Python

CSV data arrives as text. Here you’ll total units sold in three US cities:

rows = ["Austin,12", "Denver,7", "Boston,15"]

total = 0
for row in rows:
    city, qty = row.split(",")
    total += int(qty)

print("Total units:", total)
print(list(map(int, ["3", "9", "14"])))

Output:

Total units: 34
[3, 9, 14]

How does this work? int(qty) made each quantity addable, so the total is 34. map(int, ...) converts a whole list at once.

Example 5: Fix ValueError for Invalid Input with int() and try/except

You can wrap int() in a helper that returns a default for bad input:

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

for value in ["25", "3.5", "", None, " 8 "]:
    print(repr(value), "->", to_int(value))

print(int(float("3.5")))

Output:

'25' -> 25
'3.5' -> 0
'' -> 0
None -> 0
' 8 ' -> 8
3
Python int wrapped in try except returning a default for invalid strings and None in VS Code
Bad values return 0.

How does this work? “3.5” and “” raised ValueError, None raised TypeError, and all three returned 0. int(float("3.5")) handles decimal text.

Related: checking if input is a number in Python and catching multiple exceptions.

Example 6: Use int() on Booleans and Custom Objects

In Python, bool is a subclass of int, and classes can opt in with __index__():

print(int(True), int(False))

class Cents:
    def __index__(self):
        return 129900

print(int(Cents()), hex(Cents()))

Output:

1 0
129900 0x1fb6c

How does this work? True became 1. Cents has no __int__(), so int() fell back to __index__(), which hex() uses too.

Also see the Python bool() function and checking if a variable is an integer.

Common Mistakes with Python int()

Here are the Python int() errors I see most (eval() just runs each string):

tests = ['int("3.75")', 'int("1,250")', 'int(42, 2)',
         'int("010", 0)', 'int(float("nan"))']

for n, expr in enumerate(tests, 1):
    try:
        eval(expr)
    except (ValueError, TypeError) as err:
        print(f"{n}. {type(err).__name__}: {err}")

Output:

1. ValueError: invalid literal for int() with base 10: '3.75'
2. ValueError: invalid literal for int() with base 10: '1,250'
3. TypeError: int() can't convert non-string with explicit base
4. ValueError: invalid literal for int() with base 0: '010'
5. ValueError: cannot convert float NaN to integer
Common Python int errors: invalid literal, commas, explicit base with a number and NaN
Five int() errors.
  1. Decimal text: use int(float(text)).
  2. Remove commas first.
  3. base needs a string.
  4. Base 0 rejects leading zeros.
  5. NaN has no integer value.

Huge numbers have a 4,300-digit limit since Python 3.11; see the maximum int in Python.

Wrapping Up the Python int() Function

Python’s int() function turns strings, floats and number-like objects into integers. Use base for binary or hex text and try/except for bad input. In pandas, astype(int) converts a column.

Next, browse more Python built-in functions and methods.

Try these next:

Questions About Python int() Function

Does int() round up in Python?

No. It cuts toward zero, so int(9.99) is 9. Use math.ceil() to round up.

What does int(input()) do?

It reads a typed line and converts it. Non-numeric text raises ValueError.

Is int() a function or a class?

It’s a class. Calling int() builds a new integer object.

How big can a Python int be?

There’s no fixed maximum; it grows as memory allows.

Where can I read the full int() reference?

Every base and prefix rule is in int() in the Python docs.