Data Types | Numbers | Number Types

Number Types

• integers – no fractional part (Example: `4`)
• floating-point – have fractional part (Example: `4.2`)
• hexadecimal, octal, and binary literals – convert an integer to a string literal
• `int(string, base)` – converts a string to an integer in selected base
• complex numbers – have imaginary part (Example: `4 + 3j` where `j = √ -1 `)

hexadecimal `hex(x)`, octal `oct(x)`, and binary `bin(x)` literals

 0 1 2 3 4 5 6 7 8 9 a b c d e f g h i j k l m n o p q r s t u v w x y z 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35

hexadecimal (base 16) – starts with `0x`

 0 1 2 3 4 5 6 7 8 9 a b c d e f 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
``````>>> hex(0)
'0x0'
>>> hex(1)
'0x1'
>>> hex(2)
'0x2'
>>> hex(3)
'0x3'

...

>>> hex(9)
'0x9'
>>> hex(10) # 10 is a
'0xa'
>>> hex(11)
'0xb'
>>> hex(12)
'0xc'

...

>>> hex(15)
'0xf'
>>> hex(16) # it is base 16, it starts over from 0
'0x10'
>>> hex(17)
'0x11'
>>> hex(18)
'0x12'
>>> hex(19)
'0x13'

...

>>> hex(23)
'0x17'
>>> hex(24)
'0x18'
>>> hex(25)
'0x19'
>>> hex(26)
'0x1a'
>>> hex(27)
'0x1b'
...``````

octal (base 8) – starts with `0o`

 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7
``````>>> oct(0)
'0o0'
>>> oct(1)
'0o1'
'0o2'
>>> oct(3)
'0o3'
>>> oct(4)
'0o4'
>>> oct(5)
'0o5'
>>> oct(6)
'0o6'
>>> oct(7)
'0o7'
>>> oct(8)
'0o10'
>>> oct(9)
'0o11'

...

>>> oct(13)
'0o15'
>>> oct(14)
'0o16'
>>> oct(15)
'0o17'
>>> oct(16)
'0o20'
>>> oct(17)
'0o21'
...``````

binary (base 2) – starts with `0b`

 0 1 0 1
``````>>> bin(0)
'0b0'
>>> bin(1)
'0b1'
>>> bin(2)
'0b10'
>>> bin(3)
'0b11'
>>> bin(4)
'0b100'
>>> bin(5)
'0b101'
>>> bin(6)
'0b110'
...``````

`int(str, base)` – converts a runtime string to an integer per a given base

Example:

``````>>> int('dan', 24)
7751``````

The ‘n’ letter from ‘dan’ represents number 23 (take a look at the first table. The letters ‘d’ and ‘a’ are represented by lesser numbers than 23. So, the base has to be higher than 23. So, for this example 24 is
chosen as base.

Example:

``````>>> int('danro', 28)
8228860``````

The ‘r’ is number 27, so we have to choose the base to be minimum 28. So, how we get that result?

``````# danro
# d = 13 (take a look at the first table)
# a = 10
# n = 23
# r = 27
# o = 24
# There are 5 letters (from 0 to 4)

>>> 13*(28**4) + 10*(28**3) + 23*(28**2) + 27*(28**1) + 24*(28**0)
8228860``````

Let’s try it with my name:

``````>>> int('DanDumitrache', 36)
63000672758452096178``````