這可能有點愚蠢,但我已經采用了一種非常迂回的方式來驗證信用卡號。我對 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)
基本上我一直在嘗試做的是創建一個驗證,允許回圈在錯誤后繼續并回傳到回圈的開始。我已經嘗試過除了回圈之外的嘗試但它沒有用,我想就此獲得第二意見,也許可以從了解我試圖用我的代碼實作的目標的人那里獲得一些幫助。
uj5u.com熱心網友回復:
另一種可以做到這一點的方法是例外 - 這也將幫助您處理其他錯誤:
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')
uj5u.com熱心網友回復:
與其先解包,然后將它們組合成一個串列,不如反過來:
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")
作為旁注,研究生成器運算式、串列推導式和內置函式,例如all和any以進一步簡化您的代碼。例如,以下行:
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):
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/360698.html
下一篇:文本框驗證以確保只有整數值
