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:

  1. x: A number or sting to be converted to integer.
  2. 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.

Example: Convert Float and String to Int
i = int(16.5)
print(type(i))
print("float to int: ", i)

i = int('16')
print(type(i))
print("string to int: ", i)
Output
<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.

Example: Error on Float String
i = int('16.50')
Output
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.

Example: Convertion of Number Types
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))
Output
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.

Example: Error on Non-numeric String
i = int('x')
Output
Traceback (most recent call last):
    int('x')
ValueError: invalid literal for int() with base 10: 'x'
Want to check how much you know Python?