import os
class Converter(object):
def dec_to_any(self, a, b):
self.values = {0: "0", 1: "1", 2: "2", 3: "3", 4: "4", 5: "5", 6: "6", 7: "7", 8: "8", 9: "9", 10: "A", 11: "B", 12: "C", 13: "D", 14: "E", 15: "F", 16: "G", 17: "H", 18: "I", 19: "J", 20: "K", 21: "L", 22: "M", 23: "N", 24: "O", 25: "P", 26: "Q", 27: "R", 28: "S", 29: "T", 30: "U", 31: "V"}
self.universal = []
self.temp_uni = []
while a != 0:
if a < b:
self.universal.append(self.values.get(a, "unavailable"))
a -= a
else:
self.universal.append(self.values.get((a % b), "unavailable"))
a //= b
for i in range(len(self.universal) + 1):
self.temp_uni.append(self.universal[-i])
del self.temp_uni[0]
self.universal = ""
for i in self.temp_uni:
self.universal += str(i)
return self.universal
def any_to_dec(self, a, b):
a = int(a, b) #problem part 3 start and end
return a
def display(self):
print("Hello and welcome to the base converternHere is the menu:nt0 - closent1 - convertnn")
def main(self):
while True:
try:
self.display()
self.option = int(input("Please select one: "))
while self.option > 1 or self.option < 0:
os.system("cls")
self.display()
self.option = int(input("Please select one: "))
os.system("cls")
break
except:
os.system("cls")
pass
if self.option == 1:
while True:
try:
self.base1 = int(input("Please enter a base to convert from (2-32): "))
while self.base1 < 2 or self.base1 > 33:
os.system("cls")
self.base1 = int(input("Please enter a base to convert from (2-32): "))
break
except:
os.system("cls")
pass
while True:
try:
self.number = str(input("Please enter a number to convert: ")).upper()
break
except:
os.system("cls")
pass
while True: #problem part 1 start
try:
self.base2 = int(input("Please enter a base to convert to (2-36): "))
while self.base2 < 2 or self.base2 > 37:
os.system("cls")
self.base2 = int(input("Please enter a base to convert to (2-36): "))
break
except:
os.system("cls")
pass #problem part 1 end
os.system("cls")
self.return_val = self.any_to_dec(self.number, self.base1) #problem part 2 start and end
self.return_val = self.dec_to_any(self.return_val, self.base2)
print(self.number, "in base", self.base1, "would be",
self.return_val, "in base", self.base2)
start = Converter()
start.main()
这是代码,供参考。我正在制作一个基本转换器,用户在其中选择一个基础要转换到并输入一个数字,转换器吐出了转换的数字。我的困境是,用户可以输入基本2,并超过他们输入的最终呈现错误,我试图通过添加if语句来检查他们所在的基础,并且wier thile loop loop说,不要继续进行,直到没有引起字符的错误。但这很筋疲力尽。是否有一种自动化的方法可以做?喜欢:
base_2 = ["0", "1"]
如果出现了任何不在 base_2
中的东西:
some prevention code....
在我的评论中扩展,您可以从string
模块中获取数字和字母。以下是针对基本1-36的案例不敏感的文字。
from string import digits, ascii_lowercase
characters = digits + ascii_lowercase
def is_valid(literal, base):
valid_digits = characters[:base]
return set(valid_digits).issuperset(literal.lower())
is_valid('01010101', 2)
# True
is_valid('100101a', 2)
# False
is_valid('DeadBeef', 16)
# True
is_valid('123z', 16)
# False