WorldGov
WorldGov

Reputation: 157

Why does Python not accept integers starting with 0 as valid code?

I understand that you can't define a variable as, say,

height = 06

Why can't we do it? Yes, no integer starts with a zero, but given that, mathematically, 06 is the same as 6, why don't programming languages allow us to define it that way (even if has no real use) instead of throwing up an error?

Is there anything specific that would cause problems if variables are defined that way? While using or printing such a variable, the interpreter / compiler can use it as just "6", but why throw an error while we're just defining? Is it just convention?

Upvotes: 2

Views: 2287

Answers (2)

apatniv
apatniv

Reputation: 1856

Look at this pep which explains the reasoning further: https://www.python.org/dev/peps/pep-3127/#motivation

In python 2:

>>> height = 013
>>> print(height)
11
>>> print(sys.version)
2.7.12 (default, Dec  4 2017, 14:50:18) 
[GCC 5.4.0 20160609]
>>> 

Upvotes: 2

Roland Smith
Roland Smith

Reputation: 43523

If you look at the definition of integer literals, you will see:

Note that leading zeros in a non-zero decimal number are not allowed. This is for disambiguation with C-style octal literals, which Python used before version 3.0.

Both C and Python 2 used the "0x" prefix for hexadecimal numbers, and the "0" prefix for octal numbers.

Python 3 uses "0x" and "0o" respectively.

Note that you can have leading zeroes when converting from a string to an int:

In [1]: int('06')
Out[1]: 6

Upvotes: 7

Related Questions