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

Python带重试次数的登录系统如何简化?新手求助

优化带重试限制的Python登录系统

这里是简化后的代码,解决了重复输出问题,同时优化了逻辑清晰度:

max_attempts = 5
for attempt in range(max_attempts):
    password = int(input("Enter the Password: "))
    if password == 1234:
        print("ACCESS GRANTED")
        break
    remaining_attempts = max_attempts - attempt - 1
    if remaining_attempts > 0:
        print(f"INVALID PASSWORD ({remaining_attempts} times left)")
    else:
        print("Console has been locked")

优化说明:

  • 用for循环直接管理尝试次数,不需要手动更新计数器,避免了原代码中计数器与剩余次数不匹配的小问题
  • 把"ACCESS GRANTED"的输出放在一处,彻底消除重复代码
  • 剩余尝试次数的计算更准确:max_attempts - attempt - 1,因为attempt从0开始计数,第一次失败后剩余次数为4,符合实际情况
  • 当最后一次尝试失败时,直接输出锁定信息,逻辑连贯无需额外的break判断

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 01:20:33