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

Python密码生成器自定义密码校验if语句故障求助

问题排查与修复方案

让我来帮你定位这个密码校验的问题——核心错误出在你用了完全错误的方式检查密码是否包含小写、大写字母和特殊字符,具体原因和修复方法如下:

为什么当前代码会失效?

你写的password2.find(lower)、password2.find(upper)、password2.find(special)这三行有两个致命问题:

  1. lower、upper、special这三个变量大概率没有被正确定义成包含对应字符集的字符串(比如你没提前写lower = 'abcdefghijklmnopqrstuvwxyz'),直接调用会报错或者返回-1;
  2. 就算你定义了这些字符集,str.find()方法是用来查找某个特定子串是否存在,而不是检查字符串里是否包含任意一个该类别的字符。比如你用find('abc')只会找密码里有没有连续的abc,而不是找有没有任意小写字母。

你的测试密码TesT@TesT明明符合要求,却被拒就是因为这几行的逻辑完全不成立。

修复后的校验代码

我帮你重新编写了校验逻辑,用Python内置的字符判断方法和any()函数来实现正确的类别检查,同时修正了拼写错误:

# 先定义需要的特殊字符集合(你可以根据需求调整)
special_chars = "!@#$%^&*()_+-=[]{}|;:,.<>?/"

if choice == 'own':
    print("It must be more than 8 characters and should have at least a lower case, upper case and a special character")
    password2 = input("Enter your password: ")
    
    if len(password2) < 8:
        print("Doesn't meet the requirements: too short")
    elif not any(c.islower() for c in password2):
        print("Doesn't meet the requirements: missing lowercase letter")
    elif not any(c.isupper() for c in password2):
        print("Doesn't meet the requirements: missing uppercase letter")
    elif not any(c in special_chars for c in password2):
        print("Doesn't meet the requirements: missing special character")
    else:
        password = password2
        passcheck()

修复逻辑说明

  • any(c.islower() for c in password2):遍历密码的每个字符,只要有一个是小写字母就返回True;
  • any(c.isupper() for c in password2):同理检查大写字母;
  • any(c in special_chars for c in password2):检查密码里是否包含我们定义的任意一个特殊字符;
  • 每个分支还添加了更具体的错误提示,方便用户知道哪里不符合要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 19:17:50