我正在用python开发一个程序,以从任何数字基数转换为任何数字基数。我的代码如下
num = raw_input("Please enter a number: ")
base = int(raw_input("Please enter the base that your number is in: "))
convers = int(raw_input("Please enter the base that you would like to convert to: "))
if (64 < convert < 2 or 64 < base < 2):
print "Error! Base must be between 2 and 32."
sys.exit()
symtodig = {
'0': 0,
'1': 1,
'2': 2,
'3': 3,
'4': 4,
'5': 5,
'6': 6,
'7': 7,
'8': 8,
'9': 9,
'A': 10,
'B': 11,
'C': 12,
'D': 13,
'E': 14,
'F': 15,
'G': 16,
'H': 17,
'I': 18,
'J': 19,
'K': 20,
'L': 21,
'M': 22,
'N': 23,
'O': 24,
'P': 25,
'Q': 26,
'R': 27,
'S': 28,
'T': 29,
'U': 30,
'V': 31,
'W': 32,
'X': 33,
'Y': 34,
'Z': 35,
'a': 36,
'b': 37,
'c': 38,
'd': 39,
'e': 40,
'f': 41,
'g': 42,
'h': 43,
'i': 44,
'j': 45,
'k': 46,
'l': 47,
'm': 48,
'n': 49,
'o': 50,
'p': 51,
'q': 52,
'r': 53,
's': 54,
't': 55,
'u': 56,
'v': 57,
'w': 58,
'x': 59,
'y': 60,
'z': 61,
'!': 62,
'"': 63,
'#': 64,
'$': 65,
'%': 66,
'&': 67,
"'": 68,
'(': 69,
')': 70,
'*': 71,
'+': 72,
',': 73,
'-': 74,
'.': 75,
'/': 76,
':': 77,
';': 78,
'<': 79,
'=': 80,
'>': 81,
'?': 82,
'@': 83,
'[': 84,
'\\': 85,
']': 86,
'^': 87,
'_': 88,
'`': 89,
'{': 90,
'|': 91,
'}': 92,
'~': 93}
digits = 0
for character in num:
assert character in symtodig, 'Found unknown character!'
value = symtodig[character]
assert value < base, 'Found digit outside base!'
digits *= base
digits += value
digtosym = dict(map(reversed, symtodig.items()))
array = []
while digits:
digits, value = divmod(digits, convers)
array.append(digtosym[value])
answer = ''.join(reversed(array))
print "Your number in base", base, "is: ", answer
我的代码效果很好,但没有使用
if (64 < convert < 2 or 64 < base < 2):
print "Error! Base must be between 2 and 32."
sys.exit()
id 喜欢将它们带回基本变量的输入,而不是退出程序。我是 python 新手,不知道如何做这样的事情。请帮忙。