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

Python中all()函数可检测数字,为何无法识别密码缺少大写字母?

密码强度检测代码修复方案

问题根源

你代码中大写字母检测的逻辑存在错误:
all(not char.upper() for char in pswrd) 这行逻辑完全不对。char.upper()只是将字符转为大写形式,只要字符非空,它的布尔值始终为True,所以not char.upper()会一直是False,而all()函数只有所有元素都为True时才返回True,导致这个条件永远无法触发,自然检测不到缺失大写字母的情况。

核心修正

将大写字母检测的条件替换为char.isupper()方法,该方法专门用于判断字符是否为大写字母:

elif all(not char.isupper() for char in pswrd):

额外优化点

  1. 修正拼写错误:charcters → characters
  2. 移除全局变量n,改用函数返回值控制循环,避免全局变量带来的副作用

完整修正代码

import string

def spv(password):
    punct = string.punctuation
    pswrd = password
    # 调试用的print(punct)可根据需要保留或注释
    if len(pswrd) < 8:
        print("Password must be over 7 characters long!")
        return False
    elif all(not char in punct for char in pswrd):
        print("Password must contain a special character. !?, ... etc")
        return False
    elif all(not char.isupper() for char in pswrd):
        print("Password must contain at least one UPPERCASE letter!")
        return False
    elif all(not char.isdigit() for char in pswrd):
        print("Password must contain a number!")
        return False
    else:
        print("Password is Strong!")
        return True

while True:
    word = input("Write password: ")
    if spv(word):
        print("Working")
        break

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 22:30:51