Wrong math with Python?
Just starting out with Python, so this is probably my mistake, but...
I'm trying out Python. I like to use it as a calculator, and I'm slowly working through some tutorials.
I ran into something weird today. I wanted to find out 20132013, but I wrote the wrong thing and wrote 2013013, and got this:
>>> 2013*013 22143
I checked with my calculator, and 22143 is the wrong answer! 2013 * 13 is supposed to be 26169.
Why is Python giving me a wrong answer? My old Casio calculator doesn't do this...
Because of octal arithmetic, 013 is actually the integer 11.
>>> 013 11
With a leading zero,
013 is interpreted as a base-8 number and 181 + 380 = 11.
The default octal representation of integers is silently confusing to people unfamiliar with C-like languages. It is extremely easy to inadvertently create an integer object with the wrong value, because '013' means 'decimal 11', not 'decimal 13', to the Python language itself, which is not the meaning that most humans would assign to this literal.