#Use the int() function


The int() function is used to convert a given value into its  integer form. The value should be representable as an integer for the conversion to work. The value can be a float in which case decimal part will be truncated, a boolean value, a string which represents a valid integer number, user defined objects which specifies the __int__ method, etc. If no argument is given, the function simply returns 0. If an integer is given as the argument, the function returns the same integer.

int(x, base = None)
x The value that we want to cast into an integer.
base A n integer value from 2 to 36 specifying the base of conversion. It is only relevant  if the first argument( x) is a string. If it is not given base 10 will be used for conversion.

If no value is given, the function returns integer 0. Otherwise, the function convert and returns the given value as a base 10 integer.



If both arguments are passed to the function, the first argument will be converted to a base 10  integer and the second argument will be used as the base of the conversion. However, if the base is specified, the first argument must be a string, otherwise, a  TypeError will be raised .


int("100", 2)
int(100, 16)
int("10000", 8)
int(3, 8)
//TypeError: int() can't convert non-string with explicit base
intt("100", 1)
//ValueError: int() base must be >= 2 and <= 36, or 0
int("100", 37)
//ValueError: int() base must be >= 2 and <= 36, or 0

When the base is set to 0, the function automatically detects the base from the prefix of the string argument, if provided. If no prefix is present, it assumes the base as 10. Examples:

int("100", 0) # base 10
//100 (base 10)
int("0x100", 0) #base 16
int("0o100", 0) #base 8
int("0b100", 0) #base 2)

If the value given as the argument is not representable as a valid integer value in the specified base, a ValueError will be raised. Examples:

//ValueError: invalid literal for int() with base 10: 'Hello'
//ValueError: invalid literal for int() with base 10: '2.5'
int('23', 2)
//ValueError: invalid literal for int() with base 2: '23'