Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 818
WorldGov Avatar asked Jun 18 '26 16:06

WorldGov


1 Answers

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
like image 87
Roland Smith Avatar answered Jun 21 '26 02:06

Roland Smith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!