Python int()

Filed Under: Python

Python int() function returns an integer object from the specified input. The returned int object will always be in base 10.

Python int()

Python int() function syntax is:


class int(x=0, base=10)

Some important points for int() function are:

  • If no argument is provided, 0 will be returned by the int() function.
  • If integer literal argument is provided, base should not be provided. The returned int object will be in decimal even if the argument is in hexadecimal, binary or any other base.
  • For floating point argument, decimal point will be truncated and int value will be returned. There will be no rounding performed.
  • If the argument is string, it will be converted to int. If the string argument is not in base 10, then base must be provided.
  • Base argument can be provided for string, bytes and bytearray argument only. The allowed values are 0 and 2 to 36.
  • We can use int() with custom object too, in that case object __int__() function will be called. If __int__() function is not defined, then __trunc__() function will be called. If none of them are defined, then TypeError will be thrown.

Let’s look into int() function examples with different types of input arguments.

Python int() with numbers


x = int()
print(type(x))
print(x)

print(int(0xF))
print(int(0b111))

Output:


<class 'int'>
0
15
7

Python int() with float


x = int(10.043)
print(x)

x = int(10.8901)
print(x)

Output:


10
10

Notice that integer part of floating point number is returned, no rounding is performed.

Python int() with string


x = int("5")
print(x)

x = int("-0xf", base=16)
print(x)

x = int("0b111", base=2)
print(x)

Output:


5
-15
7

Python int() with bytes and bytearray


x = int(bytes("-0xf", "utf-8"), 16)
print(x)

x = int(bytearray("-20", "utf-8"))
print(x)

Output:


-15
-20

Python int() with custom object


class Emp:
    id = 0

    def __int__(self):
        print('__int__ function called')
        return self.id

    def __trunc__(self):
        print('__trunc__ function called')
        return self.id


x = Emp()
x.id = 100
print(int(x))

Output:


__int__ function called
100

If we comment __int__ function, then the output will be:


__trunc__ function called
100

If we comment both __int__ and __trunc__ functions, then we get the following error.


TypeError: int() argument must be a string, a bytes-like object or a number, not 'Emp'

Summary

Python int() function is used to convert string, bytes, bytearray and objects to an int object. The integer is always returned in base 10. We can get the same value by directly calling object.__int__() function.

You can checkout complete python script and more Python examples from our GitHub Repository.

Reference: Official Documentation

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages