Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Built-in Functions

Python int() function

Reference for Python int(): convert numbers and strings to integers, parse other bases, truncation of floats, ValueError cases and the string-length limit.

The int() function creates an integer. Given a number, it returns the whole-number part; given a string, it parses the text; given nothing, it returns 0. With a second argument it reads a string in another base such as 2, 8 or 16.

Python integers have unlimited size, so int() never overflows. Its most common job is turning text from input(), files or JSON into numbers, which is also its most common source of ValueError.

Python
print(int("42"))      # 42
print(int(3.99))      # 3
print(int("ff", 16))  # 255

Try it

Python Numbers and strings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Other bases and errors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
int(x=0)
int(x, base=10)
Name Description
x A number, or a str, bytes or bytearray containing an integer literal. Objects with __int__(), __index__() or __trunc__() also work.
base Optional, only with a string. An integer from 2 to 36, or 0 to detect the base from a prefix (0b, 0o, 0x). Default 10.

Return value: an int. Floats are truncated toward zero, not rounded.

Raises: ValueError if the string is not a valid integer in that base (including "3.5", "" and "1e3"); TypeError if x has no integer conversion, or if base is given with a non-string; OverflowError for int(float("inf")).

Usage notes

  • Truncation, not rounding. int(2.9) is 2 and int(-2.9) is -2. Use round() or math.floor() and math.ceil() for other behavior.
  • Whitespace and underscores. Leading and trailing whitespace is ignored, and single underscores between digits are allowed ("1_000").
  • Decimal strings fail. int("3.5") raises ValueError. Convert through float first if you accept decimals: int(float("3.5")).
  • Base must go with a string. int(255, 16) raises TypeError.
  • Reverse direction: bin(), oct() and hex() produce strings from integers.
  • bool is a subclass. int(True) is 1. See numeric types.
  • Huge digit strings. Since Python 3.11, converting a string of more than 4300 digits to int (in base 10) raises ValueError by default, as a safeguard against denial-of-service. It can be changed with sys.set_int_max_str_digits().
  • Methods. Integers also have methods such as bit_length() and to_bytes() (see int methods).