Python int() With Examples

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:

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

Output:

Python int() with float

Output:

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

Python int() with string

Output:

Python int() with bytes and bytearray

Output:

Python int() with custom object

Output:

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

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

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

By admin

Leave a Reply