Python 为多个输入引发自定义值错误

Python raise custom valueerror for multiple inputs

我的输入有两个值

input1, input2 = input("Enter two types of pizza separate each with a space: ").split()

我注意到如果我只输入一个值,我的程序就会终止并引发 ValueError: not enough values to unpack (expected 2, got 1)。在这种情况下,我是否能够引发我自己的自定义 ValueError 而不是终止我的程序,我可以让它简单地重新提示用户再次输入它吗?我想我可以用 while 循环来做到这一点?

这是我的尝试。

try: 
    input1, input2 = input("Enter two types of pizza separate each with a space: ").split()
    if input1 = None or input2 = None:
        raise ValueError("You must enter two types separate each with a comma")
except ValueError as err:
    print("Ensure that you enter two types separate each with a comma")

当你使用多重赋值语法a, b = <some list or tuple>时,如果左侧变量名的数量与迭代器的长度不匹配,这将立即抛出一个ValueError

更简洁的方法是这样做:

values = input("Enter two types of pizza separate each with a space: ").split()
if len(values) == 2:
    input1, input2 = values
    ...
else:
    print("You must enter two types separated by a space!")

如果要重复提示直到输入有效输入,可以在while循环中显示提示:

message = "Enter two types of pizza separated by a space: "
values = input(message).split()

# Block until exactly two words are entered
while len(values) != 2:
    print("You must enter two types of pizza separated by a space!")
    values = input(message).split()

# After while loop completes, we can safely unpack the values
input1, input2 = values
...

使用 while 循环当然可以解决问题:

input1, input2 = None, None
while input1 is None and input2 is None:
    try: 
        input1, input2 = input("Enter two types of pizza separate each with a space: ").split()
    except ValueError as err:
        print("Ensure that you enter two types separate each with a comma")

注意:正如之前的用户所发的那样,您无需提出自己的错误,因为当输入不正确时会自动提出错误。

此外,不要忘记在条件语句中使用 == 而不仅仅是 =。 :-)