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

Python逻辑运算符and/or使用问题:验证码校验if条件写法求助

Python验证码校验函数错误排查与修复

现有代码存在的问题

  • 大写字母统计逻辑错误
    循环内判断大写的代码错误使用了any(i.isupper() for i in security_code),只要整个字符串存在大写字母,每轮循环都会给data['upper']加1,最终统计值等于字符串总长度而非实际大写字母数量,是导致测试用例返回异常的核心原因。
  • 变量名拼写错误
    多条件判断中误写了不存在的变量case['lower'],运行时会直接抛出NameError异常。
  • 大写字母校验逻辑不符合规则
    现有判断强制要求data['upper'] % 2 !=0,也就是必须存在大写字母且数量为奇数,和要求的「若包含大写字母则数量为奇数,无大写字母也可」的规则不符。
  • 字母总数校验逻辑冗余(非报错类问题)
    data['upper'] + data['lower'] >= 4 本身已经覆盖了单独大写≥4、单独小写≥4的场景,后面两个OR条件属于冗余判断,可以直接省略。

修复后的完整代码

def checker_code(security_code):
    data = {'upper':0, 'lower':0, 'spec':0, 'digit':0, 'sum':0}
    spec_charact = ['!','@','#','$','%','^','&','*','(',')','?',',','.']
    if len(security_code) < 8 or len(security_code) > 30:
        return False
    for i in security_code:
        if i.isupper():
            data['upper'] = data['upper'] + 1
        if i.islower():
            data['lower'] = data['lower'] + 1
        if i in spec_charact:
            data['spec'] = data['spec'] + 1
        if i.isdigit():
            data['digit'] = data['digit'] + 1
            data['sum'] = data['sum'] + int(i)   
    if ( (data['upper'] == 0 or data['upper'] % 2 != 0) 
        and data['spec'] >= 2 
        and data['digit'] >= 2 
        and data['sum'] % 2 == 0 
        and data['upper'] + data['lower'] >=4 ):
        return True            
    else:
        return False

多条件逻辑组合说明

你原本的多个AND条件加括号包裹OR条件的组合结构是正确的,只要保证所有OR判断都放在同一层括号内,和外层的AND条件做逻辑与即可,本次问题主要是统计逻辑、变量拼写错误导致的校验失败。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 17:36:03