Python int() Method
The int() method returns an integer object constructed from a number or string or return 0 if no arguments are given.
Syntax:
int(x, base)
Parameters:
- x: A number or sting to be converted to integer.
- base: Optional. The base of the number x. Default base is 10.
Return Value:
Returns an int object.
The following converts float and string to int using the int()
method. By default, a value will be converted to base 10 decimal if no base is passed.
i = int(16.5)
print(type(i))
print("float to int: ", i)
i = int('16')
print(type(i))
print("string to int: ", i)
<class 'int'>
float to int: 16
<class 'int'>
string to int: 16
However, a string must be an integer string, not a float string, otherwise, the int()
function will raise an error.
i = int('16.50')
Traceback (most recent call last):
int('16.50')
ValueError: invalid literal for int() with base 10: '16.50'
The int()
function can also be used to convert binary, octal, and hexadecimal to an integer.
print("Binary to decimal: ",int('10000', 2))
print("Binary to decimal: ", int(0b11011000))
print("Octal to decimal: ", int('20', 8))
print("Octal to decimal: ", int(0o12))
print("Hexadecimal to decimal: ", int('10', 16))
print("Hexadecimal to decimal: ", int(0x12))
Binary to decimal: 16
Binary to decimal: 216
Octal to decimal: 16
Octal to decimal: 10
Hexadecimal to decimal: 16
Hexadecimal to decimal: 18
The specified value must be a valid number or numeric string; otherwise, it will throw an error.
i = int('x')
Traceback (most recent call last):
int('x')
ValueError: invalid literal for int() with base 10: 'x'