-7

我必须为十六进制到二进制转换器做一个程序。我让它工作正常。然而,唯一没有完全按计划进行的是输入了一个空字符串。如果输入了无效数据,则会产生错误,除非没有输入任何内容,也没有产生任何内容。没有错误出现,但它也没有做任何事情。

我将如何使空字符串出现错误?

def Binary(Hex):
    Result = ''
    ErrorFound = False
    BinaryEquivalent = ''
    for ThisHexDigit in Hex:
        if ThisHexDigit in ['1','2','3','4','5','6','7','8','9','0','A','B','C','D','E','F']:
            if ThisHexDigit == '0': BinaryEquivalent = '0'
            elif ThisHexDigit == '1': BinaryEquivalent = '1'
            elif ThisHexDigit == '2': BinaryEquivalent = '2'
            elif ThisHexDigit == '3': BinaryEquivalent = '3'
            elif ThisHexDigit == '4': BinaryEquivalent = '4'
            elif ThisHexDigit == '5': BinaryEquivalent = '5'
            elif ThisHexDigit == '6': BinaryEquivalent = '6'
            elif ThisHexDigit == '7': BinaryEquivalent = '7'
            elif ThisHexDigit == '8': BinaryEquivalent = '8'
            elif ThisHexDigit == '9': BinaryEquivalent = '9'
            elif ThisHexDigit == 'A': BinaryEquivalent = '10'
            elif ThisHexDigit == 'B': BinaryEquivalent = '11'
            elif ThisHexDigit == 'C': BinaryEquivalent = '12'
            elif ThisHexDigit == 'D': BinaryEquivalent = '13'
            elif ThisHexDigit == 'E': BinaryEquivalent = '14'
            elif ThisHexDigit == 'F': BinaryEquivalent = '15'
            Result = Result + BinaryEquivalent
        else:
            ErrorFound = True
            print('You have made a mistake')
    return Result
4

2 回答 2

1
if not hex_string:
    raise ValueError('Cannot convert empty string')
于 2012-04-04T14:48:38.860 回答
0

我经常发现自己在问字符串是否有任何长度

emptyInput = ""
if len(emptyInput): #returns 0 and will fail 
#but as the comments remind me
if emptyInput: #also returns false

现在你有几个选择。只需添加一个 else 并继续,引发错误,或要求新的输入。如果没有您的一些代码,真的很难建议最好的课程。

于 2012-04-04T14:45:37.037 回答