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.
int(number,base)
As seen in above syntax, Python int()
function takes two arguments.
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.
>>> int(1)
1
>>> int(2)
2
>>> int(1.2)
1
>>> int(9.9e5)
990000
>>> 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(0b0101)
5
>>> int(0b0111)
7
>>> int(0o11)
9
>>> int(0o111)
73
>>> int(0x11)
17
>>> int(0x111)
273