python - What does base value do in int function? -


i've read official doc https://docs.python.org/2/library/functions.html#int, still confused.

i've tried command on terminal, find rules, still not quite clear it. hope more knowledge can explain further.

below examples , findings:

int('0', base=1) valueerror: int() base must >= 2 , <=36  int('3', base=2) valueerror: invalid literal int() base 2:  int('3', base=4) 3  int('33', base=4) 15  int('333', base=4) 63  int('353', base=4) valueerror: invalid literal int() base 4: 

i find 2 rules here:

  1. the single string numbers must smaller base number.
  2. the int() return number equals (n)*(base^(n-1)) + (n-1)*(base^(n-2)) + ... + 1*(base^0)

are there other hidden rules this, , kind of problem base designed solve?

it says - converts string integer in given numeric base. per documentation, int() can convert strings in base 2 36. on low end, base 2 lowest useful system; base 1 have "0" symbol, pretty useless counting. on high end, 36 chosen arbitrarily because use symbols "0123456789abcdefghijklmnopqrstuvwxyz" (10 digits + 26 characters) - continue more symbols, not clear use after z.

"normal" math base-10 (uses symbols "0123456789"):

int("123", 10)  # == 1*(10**2) + 2*(10**1) + 3*(10**0) == 123 

binary base-2 (uses symbols "01"):

int("101", 2)   # == 1*(2**2) + 0*(2**1) + 1*(2**0) == 5 

"3" makes no sense in base 2; uses symbols "0" , "1", "3" invalid symbol (it's kind of trying book appointment 34th of january).

int("333", 4)   # == 3*(4**2) + 3*(4**1) + 3*(4**0)                 # == 3*16 + 3*4 + 3*1                 # == 48 + 12 + 3                 # == 63 

Comments

Popular posts from this blog

jQuery Mobile app not scrolling in Firefox -

c++ - How to add Crypto++ library to Qt project -

how to receive file in java(servlet/jsp) -