An integer is a whole-number value with no fractional component. Python integers can grow as large as available memory allows. They are one of Python’s numeric types, alongside floats, complex numbers, and Booleans. section 3.2.1 section 4.7
Integer arithmetic follows a few practical rules:
- Arithmetic between integers usually produces an integer; `/` produces a float, while `//` produces an integer by rounding down. section 4.7
- Use `int(value)` to convert a float or numeric string to an integer. Converting a float discards its fractional part; a string that cannot be interpreted as an integer raises `ValueError`. section 4.7 section 6.4.2
- To parse a string written in another base, pass that base as `int()`’s second argument, such as `int('101', 2)`. section 6.4.2
- `input()` returns a string, so convert it with `int()` before using it as an integer. section 4.9
x = 5 + 2 - 3 * 2 x 1 5 / 2 2.5 #1 5 // 2 2 #2 5 % 2 1 2 ** 8 256 1000000001 ** 3 1000000003000000003000000001 #3 #1 Float result using <kbd>/</kbd> #2 Result forced to integer using<kbd>//</kbd> #3 Integer size limited only by available memory
Compare integer division with `/` and `//`, and see a large integer result from exponentiation. section 3.2.1
float('123.456')
123.456
float('xxyy')
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-30-14b25c5b2052> in <cell line: 1>()
----> 1 float('xxyy')
ValueError: could not convert string to float: 'xxyy'
int('3333')
3333
int('123.456') #1
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-32-ed4c46a302ea> in <cell line: 1>()
----> 1 int('123.456')
ValueError: invalid literal for int() with base 10: '123.456'
int('10000', 8) #2
4096
int('101', 2) #3
5
int('ff', 16) #4
255
int('123456', 6) #5
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-36-bdc1281d81c5> in <cell line: 1>()
----> 1 int('123456', 6)
ValueError: invalid literal for int() with base 6: '123456'
#1 Can’t have decimal point in integer
#2 Interprets 10,000 as octal number
#3 Binary number
#4 Hexadecimal number
#5 Can’t interpret 123,456 as base 6 number
See numeric strings converted to integers, base-specific parsing, and examples that raise `ValueError`. section 6.4.2














