Python如何根据函数执行结果调用对应函数(密码校验场景)
Python密码校验+自动生成逻辑调整方案
你的现有代码存在3个核心问题导致无法实现需求:
- 密码强度校验函数没有返回校验结果,主流程无法判断是否需要触发后续密码生成操作
- 校验函数里的
while循环完全冗余,单次输入校验不需要循环包裹 - 选项选择函数的循环判断条件写错,且没有主流程串联各函数的执行顺序
调整后可直接运行的完整代码
import re import random import string # 校验密码强度 # 参数:无 # 返回值:布尔值,密码有效返回True,无效返回False def password_strength_check(): user_password = input("Enter your password: ") # 依次校验规则 if len(user_password)<6 or len(user_password)>12: print("Not a Valid Password") return False if not re.search("[a-z]",user_password): print("Not a Valid Password") return False if not re.search("[0-9]",user_password): print("Not a Valid Password") return False if not re.search("[A-Z]",user_password): print("Not a Valid Password") return False if not re.search("[$#@]",user_password): print("Not a Valid Password") return False if re.search("\s",user_password): print("Not a Valid Password") return False # 所有规则通过 print("Valid Password") return True # 生成指定长度的随机密码 # 参数:length 密码长度 # 返回值:无 def newpassword(length): characters = string.ascii_letters + string.digits + string.punctuation password = ''.join(random.choice(characters) for i in range(length)) print("Random password is:", password) # 提供密码长度选项供用户选择 # 参数:无 # 返回值:无 def options(): print("Please choose what kind of password you want") print("A: 8 character password\nB: 12 character password\nC: 16 character password ") while True: user_choice = input("> ").lower() if user_choice == "a": newpassword(8) break elif user_choice == "b": newpassword(12) break elif user_choice == "c": newpassword(16) break else: print("invalid choice, please enter A/B/C") # 主流程入口 if __name__ == "__main__": is_valid = password_strength_check() # 密码无效时,先调用选项选择函数(选完自动触发密码生成) if not is_valid: options()
核心调整说明
- 重构
password_strength_check()的返回逻辑,去掉无意义的while循环和标记变量i,命中不满足的规则直接返回False,全部通过返回True,逻辑更清晰 - 修正
options()里的循环判断,原来的条件存在笔误(重复判断"b"、逻辑运算符使用错误),改用while True的死循环,用户输入合法选项后自动跳出,输入错误则持续提示重输 - 增加主执行入口串联流程:先跑密码校验,校验不通过时直接调用
options(),用户选完长度后options()内部会自动调用newpassword()生成对应长度的随机密码,完全匹配你要的执行顺序
内容的提问来源于stack exchange,提问作者imorshed
相关产品推荐
相关产品推荐

