ExampleEdit & Run
#Use the int() function

print(int(0.1))
print(int(2.5))
print(int("10"))
copy
Output:
0 2 10 [Finished in 0.010852101258933544s]

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.

Syntax:
int(x, base = None)
copy
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.
Parameters:

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

ExampleEdit & Run
print(int())
print(int(10))
print(int(2.5))
print(int("3000"))
print(int("200"))
print(int(True))
print(int(False))
copy
Output:
0 10 2 3000 200 1 0 [Finished in 0.010947191156446934s]

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 .

ExampleEdit & Run
print(int("100", 2))

print(int(100, 16))
print(int("10000", 8))
print(int(3, 8))
print(int("100", 37))
copy
Output:
4 Traceback (most recent call last):   File "<string>", line 3, in <module> TypeError: int() can't convert non-string with explicit base [Finished in 0.01011398434638977s]

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.

ExampleEdit & Run
print(int("100", 0)) # base 10
print(int("0x100", 0)) #base 16
print(int("0o100", 0)) #base 8
print(int("0b100", 0)) #base 2)
copy
Output:
100 256 64 4 [Finished in 0.010970615781843662s]

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:

ExampleEdit & Run
print(int("2.5"))
copy
Output:
Traceback (most recent call last):   File "<string>", line 1, in <module> ValueError: invalid literal for int() with base 10: '2.5' [Finished in 0.010613185353577137s]