如何让子函数识别主函数变量?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()
问题解决说明
统一密码输入与参数传递
- 所有验证函数改为接收
password参数,不再在子函数中重复调用input() main()作为唯一入口获取用户输入,将密码传递给各验证函数
- 所有验证函数改为接收
修复空格检测问题
- 原
password.isspace()仅当整个字符串都是空格时返回True,无法检测包含空格的情况 - 改用
any(c.isspace() for c in password)遍历每个字符,只要存在空格就返回True,取反后得到“无空格”的验证结果
- 原
字母数字组合验证
- 用
any(c.isalpha() for c in password)判断是否存在至少一个字母 - 用
any(c.isdigit() for c in password)判断是否存在至少一个数字 - 两个条件同时满足时,返回验证通过
- 用
循环重新输入逻辑
- 在
main()中使用while True无限循环,直到所有验证条件都通过 - 每次验证失败后给出对应错误提示,验证通过则用
break退出循环
- 在
内容的提问来源于stack exchange,提问作者Creator Combat
相关产品推荐
相关产品推荐

