How does int(x[,base]) work?

Manshi Sanghai picture Manshi Sanghai · Nov 12, 2015 · Viewed 18.7k times · Source

The output for the following code is:

int("12", 5) 
O/P: 7

int("0", 5)
O/P: 0

int("10", 2)
O/P: 2

I cannot make sense of this. From the Python documentation it says: The "[, base]" part is optional i.e it might take one or two arguments.

The first argument should necessarily be a string which has an int value within the quotes.

Answer

Martijn Pieters picture Martijn Pieters · Nov 12, 2015

int(string, base) accepts an arbitrary base. You are probably familiar with binary and hexadecimal, and perhaps octal; these are just ways of noting an integer number in different bases:

  • binary represents a number in base 2 (0 and 1)
  • octal represents a number in base 8 (0, 1, 2, 3, 4, 5, 6 and 7)
  • decimal is what is used in daily (western) life to talk about integers, which is base 10 (0 through to 9).
  • hexadecimal is base 16 (0 through to 9, then A, B, C, D, E, F).

Each base determines how many values each 'position' in the notation can take. In decimal we count up to 9, then add a position to count the 'tens', so 10 means one times ten, zero times one. Count past 99 and you add a 3rd digit, etc. In binary there are only two digits, so after 1 you count up to 10, which is one time two, and zero times one, and after 11 you count up to 100.

The base argument is just the integer base, and it is not limited to 2, 8, 10 or 16. Base 5 means the number is expressed using digits 0 through to 4. The decimal number 10 would be 20 in base 5, for example (2 times 5).

int(string, 5) then interprets the string as a base-5 number, and will produce a Python integer to reflect its value:

>>> int('13', 5)  # one time 5, 3 times 1  == 8
8
>>> int('123', 5)  # one time 5**2 (25), 2 times 5, 3 times 1  == 38
38

If you had to name base-5 numbers it would probably be called pental.