信用卡校验器循环异常:非法输入时无法重新提示用户输入
信用卡校验器输入报错问题解决方法
核心问题解决思路
先对用户输入做前置合法性校验,确保只有纯数字(支持先去除空格)的输入才进入后续Luhn算法计算,避免非数字输入触发类型转换报错。同时优化原代码中的冗余逻辑,提升可读性。
具体步骤与修改后代码
while True: # 获取输入并预处理 inp = input("Enter a number!: ").strip() # 移除所有空格(兼容用户输入带空格的卡号格式) cleaned_card = inp.replace(" ", "") # 输入合法性校验 if not cleaned_card or not cleaned_card.isdigit(): print("请输入有效的数字卡号,不能包含字母、特殊字符或空值!") continue # ---------------------- Luhn算法实现 ---------------------- reversed_card = cleaned_card[::-1] value = 0 # 处理从右数第2、4、6...位的数字 for digit_char in reversed_card[1::2]: digit = int(digit_char) * 2 # 拆分两位数并求和 value += digit // 10 + digit % 10 # 处理从右数第1、3、5...位的数字 value_1 = sum(int(d) for d in reversed_card[0::2]) final_value = value + value_1 # 判断Luhn校验是否通过 if final_value % 10 != 0: print("INVALID") break # ---------------------- 卡类型判断 ---------------------- card_length = len(cleaned_card) first_digit = cleaned_card[0] first_two_digits = cleaned_card[:2] # Amex判断:15位,开头34或37 if card_length == 15 and first_two_digits in ("34", "37"): print("AMEX") break # Mastercard判断:16位,开头51-55 elif card_length == 16 and first_two_digits in ("51", "52", "53", "54", "55"): print("MASTERCARD") break # Visa判断:13或16位,开头4 elif card_length in (13, 16) and first_digit == "4": print("VISA") break # 合法Luhn校验但不匹配卡类型的情况 else: print("INVALID") break
关键优化点说明
输入校验逻辑:
- 用
replace(" ", "")移除所有空格,兼容带空格的卡号输入习惯 - 用
isdigit()检查是否全为数字,not cleaned_card判断是否为空输入 - 校验不通过时用
continue回到循环开头,重新触发输入提示
- 用
Luhn算法简化:
- 去掉原代码中重复的
inp_1/inp_2/inp_3/inp_4冗余赋值,直接使用清理后的cleaned_card - 用
sum(int(d) for d in ...)简化奇数位数字求和逻辑 - 直接用
final_value % 10 != 0判断Luhn校验结果,替代原代码中复杂的字符串反转判断
- 去掉原代码中重复的
卡类型判断优化:
- 用
in关键字简化多值匹配,减少冗余的elif语句 - 提前提取卡号长度、首位/前两位字符,逻辑更清晰直观
- 用
内容的提问来源于stack exchange,提问作者Mussa Zeb
相关产品推荐
相关产品推荐

