You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中if-elif条件判断异常问题求助(Luhn算法场景)

Luhn算法卡组织判断的问题修复

你代码里的多条件比较写法逻辑错误,比如first_2 == (34 or 37)这种写法完全达不到“判断first_2是34或者37”的效果。因为Python中or是逻辑运算符,34 or 37会直接返回34(只要第一个值为布尔真,or就返回它),所以这个条件等价于first_2 == 34,37的情况永远不会被匹配。同理length == (13 or 16)等价于length ==13,16的情况也不会触发——这就是你觉得条件为真却不执行、else分支乱生效的原因。

正确的多值比较方式

Python里判断一个值是否属于多个可选值,有两种常用方式:

  1. 使用in操作符(推荐,代码更简洁)
    把要匹配的值放进集合或列表,用in判断是否包含:
  • 运通(AMEX):first_2 in {34, 37} and length ==15
  • 万事达(MASTERCARD):first_2 in {51,52,53,54,55} and length ==16
  • 维萨(VISA):first_1 ==4 and length in {13,16}
  1. 完整写出每个比较条件,用or连接
    如果不想用in,就把每个比较都写完整,比如:first_2 ==34 or first_2 ==37,而不是把or和值放在括号里。

修改后的完整代码

if (digit + number_add2) % 10 == 0 and length >= 13:  # 校验Luhn算法是否通过
    if first_2 in {34, 37} and length == 15:
        print("AMEX")
    elif first_2 in {51, 52, 53, 54, 55} and length == 16:
        print("MASTERCARD")
    elif first_1 == 4 and length in {13, 16}:
        print("VISA")
    else:
        print("INVALID1")  # 过了Luhn但不属于指定卡组织
else:
    print("INVALID2")  # 没通过Luhn算法

内容的提问来源于stack exchange,提问作者Lavakara

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 08:03:34