Python int() Function (with Examples)

python programs

The int() is a built-in function in Python that returns the integer object of the passed number or string as a parameter.

Syntax:

int(object, base)

int() Parameters

ParameterConditionDescription
objectOptionalA Python object of types such as float, string, etc needs to be converted to an integer.
baseOptionalThe base value for the conversion.

For no argument the int() function returns 0.

The base is required only for string objects. For numbers, the base value by default is 10.

Python int() Examples

Example 1: passing Integers

>>> print(int())
0
>>> print(int(2))
2
>>> print(int(15))
15

Example 2: passing Floating Numbers

>>> print(int(2.6))
2
>>> print(int(6.1))
6

Example 3: passing String

If the base is not specified, by default it will be 10.

>>> print(int('111'))
111

#binary to decimal
>>> print(int('111',2))
7

#binary to octal
>>> print(int('111',8))
73

Example 4: passing Binary

Prefix the value with 0b or 0B, if the object is binary.

In such a case, we don’t need to pass any argument for the base. If we don’t do so, we will get an error from Python because the base is only used with string objects.

>>> print(int(0b111))
7
>>> print(int(0b101))
5

Example 5: passing Octal

To pass Octal prefix it with 0c or 0C.

#octal to decimal
>>> print(int(0o111))
73
>>> print(int(0o10)
8

Example 5: passing Hexadecimal

To pass Hexadecimal prefix it with 0x or 0X.

#hexadecimal to decimal
>>> print(int(0x10)
16
>>> print(int(0x101))
257

In summary, the int() function transforms an object into an integer in Python. It converts only those objects that has a base value.

Leave a Reply

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