pythonmathfloor-division

In Python, why does 04000 // 1000 return 2?


I am trying to separate a 5 digit number into its digits using floor division followed by modulo for each digit. Why does 04000 // 1000 return 2?

>>> 04//1
4
>>> 040//10
3
>>> 0400//100
2
>>> 04000//1000
2
>>> 4//1
4
>>> 40//10
4
>>> 400//100
4
>>> 4000//1000
4

Solution

  • Because octal numbers in Python 2 start with a 0. It is really 2048 decimal.

    >>> 04000
    2048
    

    Python 3 changes this behavior to use 0o as the modifier for octal:

    >>> 04000
      File "<stdin>", line 1
        04000
            ^
    SyntaxError: invalid token
    >>> 0o4000
    2048