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

0123456789abcdefghijklmnopqrstuvwxyz
01234567891011121314151617181920212223242526272829303132333435

hexadecimal (base 16) – starts with 0x

0123456789abcdef
0123456789101112131415
>>> 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

01234567
01234567
>>> 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

01
01
>>> 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

Leave a Reply