如何进行验证循环以确保用户在 .split 输入中输入正确的次数?

How do I make a validation loop to make sure the user inputs the correct amount of times in a .split input?

这可能有点愚蠢,但我已经采用了一种非常迂回的方式来验证信用卡号。我在 python 还是个新手,一般来说我都在编码,所以我想制作它以便我可以验证数字的数量,无论输入是否为数字,并制作它以便我可以打印输入像这样拆分:xxx-xxxx-xxxx

到目前为止我已经有了这个(请原谅它有多乱,而且可能很多都是不必要的!)

CreditOne = 0
CreditTwo = 0
CreditThree = 0

while True:
    CreditOne, CreditTwo, CreditThree = input("Enter the credit card number (separate with spaces): ").split()
    CreditCardList = [CreditOne, CreditTwo, CreditThree]
    CreditCardNumber = "-".join(CreditCardList)
    if CreditOne.isdigit() and CreditTwo.isdigit() and CreditThree.isdigit() and len(CreditOne) == 4 and len(CreditTwo) == 4 and len(CreditThree) == 4:
        break
    elif CreditOne == 0 or CreditTwo == 0 or CreditThree == 0:
        print("Please input a valid credit card number.")
        continue
    else:
        print("Please input a valid credit card number.")
        continue

print(CreditCardNumber)

它完成了大部分工作,除了如果用户只是输入类似 4 4 或类似单数字母的内容,它将得到一个 ValueError:

ValueError: not enough values to unpack (expected 3, got 1)

基本上我一直在尝试做的是创建一个验证,允许循环在错误发生后继续,return 到循环开始。我尝试了一个 try except 循环但它没有用,我想就此获得第二意见,也许有人了解我试图用我的代码实现什么的帮助。

不是先解包,然后将它们组合成一个列表,而是反过来做:

CreditCardList = input("Enter the credit card number (separate with spaces): ").split()
if len(CreditCardList) == 3:
    CreditOne, CreditTwo, CreditThree = CreditCardList
    # ... do other stuff
else:
    print("You must enter exactly 3 numbers")

作为旁注,研究生成器表达式、列表理解和内置函数(例如 allany 以进一步简化您的代码。例如,下面一行:

if CreditOne.isdigit() and CreditTwo.isdigit() and CreditThree.isdigit() and len(CreditOne) == 4 and len(CreditTwo) == 4 and len(CreditThree) == 4:

可以改写为

if all(c.isdigit() and len(c) == 4 for c in CreditCardList):

您可以执行此操作的另一种方法是处理异常 - 这也将帮助您处理其他错误:

while True:
     try:
          CreditOne, CreditTwo, CreditThree = input("Enter the credit card number (separate with spaces): ").split()
         break
     except ValueError:
         print('Oops! That's not a valid number')