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

Python密码验证程序问题:添加字母校验后功能异常求助

Python密码校验程序修复方案

核心问题分析

你的代码出现问题的根本原因是误用了字符串方法isdigit()和isalpha():

  • isdigit()返回True的前提是整个字符串全是数字,而非包含至少一个数字
  • isalpha()返回True的前提是整个字符串全是字母,而非包含至少一个字母
    同时,原代码的校验逻辑是分段循环,导致后续输入可能绕过之前的校验(比如修改字母问题时输入了长度不符合的密码),且未实现空格校验。

修复后的完整代码

# --- Main ----------
def main():
    # 显示学生信息
    studentInfo()
    # 显示欢迎信息
    welcomeMsg()
    # 提示用户输入密码
    passWord = input("\nPlease create a password:\n")
    # 调用密码校验函数
    passWord = correctPW(passWord)

# --- Functions ----------
# 学生信息
def studentInfo():
    print("\nName:\tNAME")
    print("Class:\tCMIS102")
    print("Date:\t26 July 2022")

# 欢迎信息
def welcomeMsg():
    print("\nThis program will prompt the user to enter a password with the following requirements:")
    print("\t- No less than 6 characters in length")
    print("\t- No more than 12 characters in length")
    print("\t- No spaces")
    print("\t- At least one numerical digit")
    print("\t- At least one alphabetical character")

# 密码校验函数
def correctPW(passWord):
    # 循环校验直到所有条件满足
    while True:
        errors = []
        # 校验长度
        if not (6 <= len(passWord) <= 12):
            errors.append("长度必须在6-12个字符之间")
        # 校验是否包含至少一个数字
        if not any(c.isdigit() for c in passWord):
            errors.append("必须包含至少一个数字")
        # 校验是否包含至少一个字母
        if not any(c.isalpha() for c in passWord):
            errors.append("必须包含至少一个字母")
        # 校验是否包含空格
        if ' ' in passWord:
            errors.append("不能包含空格")
        
        # 没有错误则退出循环
        if not errors:
            break
        
        # 输出错误信息并重新输入
        print("\nSorry! Your password is invalid.")
        for err in errors:
            print(f"- {err}")
        passWord = input("\nPlease create a password:\n")
    
    # 验证通过提示
    print("\nCongratulations! Your password is valid!")
    return passWord

# --- Execute ----------
main()

关键修改说明

  1. 替换校验逻辑:用any(c.isdigit() for c in passWord)遍历字符串,检查是否存在至少一个数字;字母校验同理。
  2. 整合循环校验:将所有校验放在一个while True循环中,确保每次输入都经过完整的规则检查,避免绕过之前的校验。
  3. 添加空格校验:通过' ' in passWord检查密码是否包含空格。
  4. 优化错误提示:收集所有错误一次性告知用户,提升体验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 03:33:27