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

时间:2018-03-09 06:54:20

标签: python python-3.x

这是我使用步骤

将二进制数转换为十进制数的示例代码
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,它仍会继续执行该程序。

1 个答案:

答案 0 :(得分:0)

是否必须是自定义代码?否则你可以使用ToJSON。 例如:

FromJSON

支持this answer

如果你想自定义,你可以这样做:

T