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

Python实现密码格式校验时无法退出while循环的问题排查

问题描述

我是Python及编程初学者,近期尝试开发密码格式校验程序,用于验证用户输入的密码是否满足预设规则。测试时发现即便输入符合格式要求的密码,程序也无法正常退出while循环,多次排查未定位到错误点,原实现代码如下:

low = ['abcdefghijklmnopqrstuvwxyz']
up = ['ABCDEFGHIJKLMNOPQRSTUVWXYZ']
cr = ['@$%&']
digito = ['0123456789']
counter1 = 0
tries = True
while tries:
    length = False
    May = False
    Minus = False
    Num = False
    Char = False
    counter1 += 1
    password = input('Password: ')
    if len(password) > 7 and len(password) < 16:
        length = True
    for caracter in password:
        if caracter in low:
            Minus = True
        if caracter in up:
            May = True
        if caracter in cr:
            Char = True
        if caracter in digito:
            Num = True
    if length and May and Minus and Num and Char:
        print('Password ok.')
        passw = password
        tries = False
    if counter1 == 5:
        print('You had 5 attemps.')
        break
错误定位
  • 根因是字符集定义错误:你将小写字母、大写字母、特殊字符、数字都定义为了仅包含1个长字符串元素的列表。以low = ['abcdefghijklmnopqrstuvwxyz']为例,这个列表里只有1个元素——完整的26位小写字母组成的长字符串,而非26个独立的单字符元素。
  • 后续遍历密码逐字符判断时,caracter in low的逻辑是判断当前单个字符是否和列表里的那个长字符串完全相等,正常输入场景下永远不可能匹配成功,因此Minus、May、Char、Num四个标记位始终为False,永远无法触发tries = False的退出逻辑,循环自然无法正常结束。
  • 额外注意:现有长度判断逻辑为len(password) > 7 and len(password) < 16,仅支持8-15位长度密码,如果规则要求支持16位密码,需要将条件调整为len(password) <=16。
修复后代码

只需要移除四个字符集外层的列表符号,将其定义为普通字符串即可(Python字符串本身是可迭代序列,支持单字符成员判断),修复后的代码如下:

# 去掉外层[],直接定义为字符串
low = 'abcdefghijklmnopqrstuvwxyz'
up = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
cr = '@$%&'
digito = '0123456789'
counter1 = 0
tries = True
while tries:
    length = False
    May = False
    Minus = False
    Num = False
    Char = False
    counter1 += 1
    password = input('Password: ')
    # 如需支持16位密码,把<16改成<=16即可
    if 7 < len(password) < 16:
        length = True
    for caracter in password:
        if caracter in low:
            Minus = True
        if caracter in up:
            May = True
        if caracter in cr:
            Char = True
        if caracter in digito:
            Num = True
    if length and May and Minus and Num and Char:
        print('Password ok.')
        passw = password
        tries = False
    if counter1 == 5:
        print('You had 5 attemps.')
        break

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.31 00:48:16