如何在Python中检查列表中的错误?

2024-04-19 14:59:48 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我用步骤将二进制数转换成十进制数的示例代码

def binaryToDecimal(b2d):
    i = len(b2d) - 1
    total = 0
    for x in b2d:
        print("%d x 2^%d = %d" % (x, j, (x * 2 ** j)))
        total += (x * 2 ** j)
        j -= 1
    print("The decimal conversion would be", total)


binaryToDecimal([int(n) for n in input('Enter value: ')]) # this converts user input into a list

我想它显示一个错误消息,如果用户输入了数字以外的1和0的

这是我的看法:

def binaryToDecimal(b2d):
    if 1 and 0 in b2d:
        *<proceed with program>*
    else:
        print("ERROR")

至于上面这个例子的问题,它在某些情况下工作得很好,但是为了让程序继续,必须同时输入数字1和0。 因此,输入'11'会产生错误。对于一些数字,比如'0222',即使列表中有一个2,它仍然会继续执行程序。你知道吗


Tags: 代码in示例forinputlendef错误
1条回答
网友
1楼 · 发布于 2024-04-19 14:59:48

必须是自定义代码吗?否则您可以直接使用int()。 例如:

valid = int('010101', base=2)
invalid = int('012345', base=2)

this answer的道具。你知道吗

如果您确实想定制,您可以这样做,例如:

def binaryToDecimal(b2d):
    try:
        output = int(b2d, base=2)
        print output
    except ValueError as e:
        custom_error_message = ('your custom error message\n'
                                '(original message: {})'.format(e.message))
        raise ValueError(custom_error_message)
    return output

相关问题 更多 >