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

如何修改Python代码为用户名和密码设置3次输入尝试并修复异常?

解决用户名和密码各3次尝试的注册逻辑问题

你的原代码存在漏洞:如果3次都输入了已存在的用户名(或不符合长度要求的密码),程序依然会继续执行后续步骤,最终输出无效的账号信息。之前误用range(2)会直接减少一次尝试机会,进一步导致逻辑错误。

以下是修正后的代码,完全满足「用户名和密码各3次尝试机会,失败则终止注册」的需求:

userNames = ["User1", "User2", "User3", "User4", "User5"]
print("Welcome to AQA User Registration")

# 用户名输入逻辑:3次尝试
valid_username = False
for _ in range(3):
    userName = input("New username: ")
    if userName in userNames:
        print("The username is already used")
    else:
        valid_username = True
        break

# 3次都失败则终止程序
if not valid_username:
    print("3 username attempts failed, registration terminated")
    exit()

# 密码输入逻辑:3次尝试
valid_password = False
for _ in range(3):
    userPassword = input("Password (12 characters or more): ")
    if len(userPassword) < 12:
        print("The password is not long enough")
    else:
        valid_password = True
        break

# 3次都失败则终止程序
if not valid_password:
    print("3 password attempts failed, registration terminated")
    exit()

# 注册成功提示
print(f"Your username is {userName}")
print(f"Your password is {userPassword}")

关键修改说明

  • 增加valid_username和valid_password标记变量,明确判断是否在3次尝试内输入了有效信息
  • 若某一环节3次尝试全部失败,直接终止程序,避免执行后续无效流程
  • 用_代替x作为循环变量,符合Python编码习惯(无需使用循环变量时的写法)
  • 改用f-string格式化输出,比字符串拼接更简洁、可读性更强

内容的提问来源于stack exchange,提问作者Computer AI

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 03:01:12