int()

Converts a value to an integer.

Returns
An integer.
On this page

Example

#
Python
print(int("42"))
print(int(3.9))
print(int(-3.9))
print(int("ff", 16))
print(int(" 1_000 "))
Resultsaved result, you can check it
42
3
-3
255
1000

Definition and usage

#

The int() function creates an integer from a string, a float, or a boolean value. From a float it cuts off the fractional part without rounding, so int(3.9) is 3.

A string must contain a valid integer. Leading and trailing spaces and underscores between digits are allowed. Text like "3.5" or "12 kg" raises a ValueError.

The second argument is the base of the number system: int("ff", 16) gives 255, and int("1010", 2) gives 10. Integers in Python have no size limit.

Syntax

#
Syntax
int(x)
int(string, base)

Parameters

#
  • x

    a string, float, or bool

    The value to convert.
  • base

    int 2-36, optional

    The base of the number system for strings.

More examples

#
An invalid string
Python
try:
    int("3.5")
except ValueError as error:
    print(error)
Resultsaved result, you can check it
invalid literal for int() with base 10: '3.5'

Good practices

#
  • To round to the nearest number use round(), not int(), which only truncates.
  • Always wrap the conversion of user-typed text in a try block with except ValueError.

Related entries

#

Spotted a mistake or missing an example? Write to us.