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

如何让子函数识别主函数变量?Python密码验证程序整合求助

密码验证程序解决方案

修正后的完整代码

def passLength(password):
    return 5 < len(password) < 15

def passSpace(password):
    # 检查是否包含任意空格字符
    return not any(c.isspace() for c in password)

def passAlphaNum(password):
    # 检查是否同时包含至少一个字母和数字
    has_alpha = any(c.isalpha() for c in password)
    has_digit = any(c.isdigit() for c in password)
    return has_alpha and has_digit

def main():
    while True:
        password = input("Enter password: ")
        # 逐一验证所有条件
        length_ok = passLength(password)
        space_ok = passSpace(password)
        alnum_ok = passAlphaNum(password)
        
        if not length_ok:
            print("密码长度无效,需6-15位,请重新输入")
        elif not space_ok:
            print("密码包含空格,请重新输入")
        elif not alnum_ok:
            print("密码需同时包含至少一个字母和数字,请重新输入")
        else:
            print("密码验证通过!")
            break

if __name__ == "__main__":
    main()

问题解决说明

  1. 统一密码输入与参数传递

    • 所有验证函数改为接收password参数,不再在子函数中重复调用input()
    • main()作为唯一入口获取用户输入,将密码传递给各验证函数
  2. 修复空格检测问题

    • 原password.isspace()仅当整个字符串都是空格时返回True,无法检测包含空格的情况
    • 改用any(c.isspace() for c in password)遍历每个字符,只要存在空格就返回True,取反后得到“无空格”的验证结果
  3. 字母数字组合验证

    • 用any(c.isalpha() for c in password)判断是否存在至少一个字母
    • 用any(c.isdigit() for c in password)判断是否存在至少一个数字
    • 两个条件同时满足时,返回验证通过
  4. 循环重新输入逻辑

    • 在main()中使用while True无限循环,直到所有验证条件都通过
    • 每次验证失败后给出对应错误提示,验证通过则用break退出循环

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 00:50:21