int() in Python is a built-in function that returns the corresponding integer object of passed number or string as a parameter.
Syntax:
int(object, base)
int() Parameters
object [optional] – Any object like integer, float, string, etc that need to be converted to integer.
base [optional] – Base value for the conversion.
If no argument is passed then int() returns 0
as a result.
base is required only for string object passed as the first argument. For numbers, the default base value is 10
.
Python int() Examples
Example 1: passing Integers
>>> print(int()) 0 >>> print(int(2)) 2 >>> print(int(15)) 15
Example 2: passing Floating Numbers
>>> print(int(2.6)) 2 >>> print(int(6.1)) 6
Example 3: passing String
If base not specified, by default it would be 10
.
>>> print(int('111')) 111 #binary to decimal >>> print(int('111',2)) 7 #binary to octal >>> print(int('111',8)) 73
Example 4: passing Binary
To pass binary, prefix it with 0b
or 0B
. Do not pass any argument for base otherwise it will throw error because base is only used with string object.
>>> print(int(0b111)) 7 >>> print(int(0b101)) 5
Example 5: passing Octal
To pass Octal prefix it with 0c
or 0C
.
#octal to decimal >>> print(int(0o111)) 73 >>> print(int(0o10) 8
Example 5: passing Hexadecimal
To pass Hexadecimal prefix it with 0x
or 0X
.
#hexadecimal to decimal >>> print(int(0x10) 16 >>> print(int(0x101)) 257
So, use int() to convert any numbers or string into an integer if possible in Python.
If you have any doubts or suggestion then comment below.