Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
340 views
in Technique[技术] by (71.8m points)

python - What does base value do in int function?

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

I've tried some command on my terminal, I find some rules, but still not quite clear about it. Hope someone with more knowledge about this can explain it further.

Below are my examples and findings:

int('0', base=1)
ValueError: int() base must be >= 2 and <=36

int('3', base=2)
ValueError: invalid literal for int() with base 2:

int('3', base=4)
3

int('33', base=4)
15

int('333', base=4)
63

int('353', base=4)
ValueError: invalid literal for int() with base 4:

I find two rules here:

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

Are there any other hidden rules than this, and what kind of problem the base is designed to solve?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It does exactly what it says - converts a string to integer in a given numeric base. As per the documentation, int() can convert strings in any base from 2 up to 36. On the low end, base 2 is the lowest useful system; base 1 would only have "0" as a symbol, which is pretty useless for counting. On the high end, 36 is chosen arbitrarily because we use symbols from "0123456789abcdefghijklmnopqrstuvwxyz" (10 digits + 26 characters) - you could continue with more symbols, but it is not really clear what to use after z.

"Normal" math is base-10 (uses symbols "0123456789"):

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

Binary is 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; it only uses symbols "0" and "1", "3" is an invalid symbol (it's kind of like trying to book an appointment for the 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...