Python Notes

# The int() function

In the Python programming language, the `int()` built-in function returns an integer (an instance of the int class) in decimal number system. If the argument passed to the function cannot be converted to a decimal number, a `ValueError` exception is thrown.

If you call the `int()` function without arguments, it will return 0.

``````>>> int()
0``````

Most often, the `int()` function is passed a single argument, which can be either a string or a number. Strings must be character representations of an integer, otherwise an exception will be thrown.

``````>>> int('4')
4
>>> int('3a')
Traceback (most recent call last):
File "<pyshell#29>", line 1, in <module>
int('3a')
ValueError: invalid literal for int() with base 10: '3a'``````

If you pass an integer to the function, it will return it. If you pass a real number (`float` type), then it will be rounded to the nearest integer towards zero (i.e., the fractional part will be discarded).

``````>>> int(87)
87
>>> int(-103)
-103
>>> int(234.879)
234
>>> int(-0.3)
0
>>> int(-0.9)
0``````

An attempt to convert a string containing a float number to an integer using the `int()` function causes an error.

``````>>> int('101.1')
Traceback (most recent call last):
File "<pyshell#37>", line 1, in <module>
int('101.1')
ValueError: invalid literal for int() with base 10: '101.1'``````

To convert a fractional number in string representation to an integer, you can first use the `float()` function, then `int()`.

``````>>> int(float('15.76'))
15``````

When a second argument is given to the `int()` function, the first must always be a string. The second argument indicates the base of the number system of the first argument. The `int()` function returns its value in decimal notation.

``````>>> int('12', 8)
10
>>> int('13h', 20)
477
>>> int('111001', 2)
57``````

The radix base must not exceed 36.

``````>>> int('w0y', 36)
41506
>>> int('w0y', 37)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: int() base must be >= 2 and <= 36, or 0``````

Prefixes can be used for binary, octal and hexadecimal number systems. If such a number representation is enclosed in quotations, then the second argument is required.

``````>>> int(0b11)
3
>>> int(0o10)
8
>>> int(0xA5)
165
>>> int('0b11')
Traceback (most recent call last):
File "<pyshell#48>", line 1, in <module>
int('0b11')
ValueError: invalid literal for int() with base 10: '0b11'
>>> int('0b11', 2)
3``````

In classes, the `int()` function is overridden by the `__int__()`, `__index__()`, `__trunc__()` methods.

``````>>> class A:
...     a = 'H'
...     def __int__(self):
...             return ord(self.a)
...
>>> obj = A()
>>> int(obj)
72
>>> obj.a = '!'
>>> int(obj)
33
``````