0

Why is this happening?:

>>> int('20', 3)
6
>>> int('8', 3)

Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    int('8', 3)
ValueError: invalid literal for int() with base 3: '8'

Yes, I have seen this post: ValueError: invalid literal for int() with base 10: ''

But '8' does not have any decimals. Nor does it have any whitespace. Why isn't this working? Surely 8 is possible to represent in base 3.

Community
  • 1
  • 1
user124384
  • 400
  • 1
  • 9
  • 22

1 Answers1

2

Why isn't this working?

Because 8 is invalid integer in base 3. Base 3 only allows integers from 0 (inclusive), to 2 (exclusive), thus causing the ValueError.

Surely 8 is possible to represent in base 3.

Yes, but that's not what int() does. It converts a representation to a number.

>>> int('22', 3)
8

As seen above, int takes in a number in the specified base, them converts it to an integer.

Andrew Li
  • 55,805
  • 14
  • 125
  • 143
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358