How does python interpret numbers with leading zeroes

后端 未结 2 538
孤城傲影
孤城傲影 2020-11-27 08:42

I\'m new with python, I\'m using python 2.7 when I typed this on python shell:

print 01
print 010
print 0100
print 01000

It gives this resu

2条回答
  •  余生分开走
    2020-11-27 08:58

    Python interprets a number starting with 0 as octal which is base 8.You can work out the base using the binary string 10 as b^1 === b where b is the base.

    # print the decimal value of the binary number 10
    >>> print 0b10
    2
    # print the decimal value of the octal number 10    
    >>> print 010
    8
    # print the decimal value of the hexadecimal number 10
    >>> print 0x10
    16
    

    In any base the symbol 1 is always the decimal value 1 because b^0 === 1 for all b as reading right to left the index of a number starts at 0.

    # print the decimal value of the binary number 1
    >>> print 0b001
    1
    # print the decimal value of the octal number 1
    >>> print 0001
    1
    # print the decimal value of the hexadecimal number 1
    >>> print 0x001
    1
    

    Once the base is interpreted (0,0b,0x) leading 0 aren't important.

    The number of symbols needed for a base is b where the largest symbols is equal to b-1

                Base (b)   Number of Symbols (b)    Symbols (0 : b-1)
    Binary      2          2                        0,1
    Octal       8          8                        0,1,2,3,4,5,7,6,7
    Decimal     10         10                       0,1,2,3,4,5,7,6,7,8,9
    

    The largest value that can be represented by a number is (b^n)-1 where n is the number of digits. Given a 3 digit number the largest decimal value is (10^3)-1 = 999, in octal (8^3)-1 = 511 (decimal) which is 777 in base 8 and in binary (2^3)-1 = 7 (decimal) which is 111 in base 2. So you can see that with less symbols (a lower base) the value you can represent decreases given a fixed number of digits.

提交回复
热议问题