Python int() is a built-in function that returns an integer object constructed from a number or string passed as an argument or returns 0 if no arguments are given.

python int() function

Python int() Syntax

int(number,base)

As seen in above syntax, Python int() function takes two arguments.

  • number (optional) – it can be int, float or string
  • base (optional) – it is used only when the supplied number is a string

If no any argument is supplied, the int() function will simply return 0.

The default base value is 10 and it can be 0 or any number between 2 to 32. Binary (base 2), octal ( base 8) or hexadecimal (base 16) numbers can be optionally prefixed with 0b/0B, 0o/0O/0, or 0x/0X, as with integer literals in code.

Python int() Example

int() for integers

>>> int(1)
1
>>> int(2)
2

int() for floating point numbers

>>> int(1.2)
1
>>> int(9.9e5)
990000

int() for string

>>> int('0111', 2)
7
>>> int('0111', 8))
73
>>> int('0111', 16)
273

Note: With strings, the base value must be supplied for corresponding integers, else it will take 10 as default base value.

For example, without base value 16, 0111 will simply be 111 as it takes 10 as default base value.

>>> int('0111')
111

int() for binary numbers

>>> int(0b0101)
5
>>> int(0b0111)
7

int() for octal numbers

>>> int(0o11)
9
>>> int(0o111)
73

int() for hexadecimal numbers

>>> int(0x11)
17
>>> int(0x111)
273