59

I'm a beginner in python and I'm trying to use a octal number in my script, but when I try it, it returns me that error:

>>> a = 010
SyntaxError: invalid token (<pyshell#0>, line 1)
>>> 01
SyntaxError: invalid token (<pyshell#1>, line 1)

There's something wrong with my code? I'm using Python3 (and reading a python 2.2 book)

SilentGhost
  • 307,395
  • 66
  • 306
  • 293
Rafael
  • 593
  • 1
  • 4
  • 5
  • There may be something wrong with your Python installation or the shell you are using. Try the same thing at http://shell.appspot.com and see if you get the same errors. – Gene Goykhman Dec 03 '09 at 05:43
  • 1
    @Gene: As explained elsewhere, octals must be written with prefix '0o' in Python3, not just '0' as in Python 2, which now yields an error. (*Sigh*) – Max Jun 28 '21 at 22:30

1 Answers1

84

Try 0o10, may be because of python 3, or pyshell itself.

PEP says,

octal literals must now be specified with a leading "0o" or "0O" instead of "0";

http://www.python.org/dev/peps/pep-3127/

YOU
  • 120,166
  • 34
  • 186
  • 219
  • 15
    I wish every language required this for octal numbers; how stupid was using a lead 0. Now if we can just get support for 0sNNN (for sexagesimal) and put base-64 numbers into our code. – Lawrence Dol Dec 03 '09 at 07:15
  • 2
    Think of the possibilities for magic constants... no longer being constrained to `0xdeadbeef`, etc. :o – Andrew Keeton Dec 03 '09 at 08:55
  • 1
    @Rafael I think you mean "0o", not "Oo" :) – jchl Mar 09 '11 at 10:41
  • 8
    Is there any method that works in both Py3 and Py2.7? – Cerin Apr 15 '16 at 23:57
  • 9
    Yes. Using the Python3 syntax works for both Python2 and Python3. – Ben Elgar Nov 11 '16 at 19:59
  • 1
    Which also means that, finally, in Python3, `0` is no longer octal ([unlike in C](http://stackoverflow.com/questions/6895522/is-0-a-decimal-literal-or-an-octal-literal)). – gerrit Apr 07 '17 at 11:14
  • But they do allow 00 without error, which is inconsistent with throwing an error for cases 01, ..., 07 where the leading 0 does not make any difference. (And why "finally", as if that was an achievement? Why should 0 not be octal? There's not any reason to prefer 0 to be base 10 rather than base 8 or base 2...) – Max Jun 28 '21 at 22:37