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

登录项目代码执行顺序问题求助:选择退出后程序未终止

登录程序执行顺序问题修复方案

问题核心分析

你的代码存在两个关键问题:

  • 未根据菜单选择控制后续流程:当用户输入2选择结束程序时,menu()函数仅跳出内部循环,但后续的admin_login()、new_account()等函数是全局直接调用的,无论菜单结果如何都会执行。
  • 异常处理逻辑错误:菜单的异常处理使用递归调用menu(),会导致调用栈累积,容易引发栈溢出,不符合循环输入的需求。

修复后的完整代码

print("----------------------Welcome User----------------------\n\n")

# 用于输出分隔线的函数
def linebreak():
    print("---------------------------------------------------------")

# 主菜单函数,返回用户的选择结果
def menu():
    while True:
        print("-----------------------Main Menu------------------------\n")
        print("To login enter 1:")
        print("To end the program enter 2:")
        print("")
        try:
            sUserSelection = int(input("What would you like to do? \n"))
            if sUserSelection == 1:
                return sUserSelection
            elif sUserSelection == 2:
                print("Ending program, Goodbye!")
                return sUserSelection
        except ValueError:
            print("ERROR! Invalid choice please choose from the menu to continue or exit the program.\n")
            # 回到循环开头重新输入,替代递归调用
            continue

# 获取用户菜单选择
user_choice = menu()

# 仅当用户选择1时,才执行后续登录流程
if user_choice == 1:
    # 欢迎用户函数
    def welcome_user():
        print("Login successful. ")
        print("Welcome ")

    # 管理员登录相关配置
    sAdmin = "admin"
    sAdminPassWord = "aDmin002"

    def admin_login():
        print("Please login to the administrator account to create your new personal account: \n")
        while True:
            sUserInput = input("Please enter admin username: \n")
            sUserInput = sUserInput.lower()
            if sUserInput == sAdmin:
                break
            else:
                print("Wrong username please try again! \n")

        while True:
            sPassInput = input("Please enter admin password: \n")
            if sPassInput == sAdminPassWord:
                print("Login Successful")
                break
            else:
                print("Wrong password please try again! \n")

    # 创建新账户函数
    def new_account():
        print("\nPlease create a new account.\n")
        global sNewUser1
        while True:
            sNewUser1 = input("\nPlease enter a new username.\n"
                            "It should be at least 5 characters long\n"
                            "and not contain spaces or special characters: \n\n")

            if len(sNewUser1) < 5:
                print("Your username is too short. Please try again: ")
            elif sNewUser1.count(" ") > 0:
                print("Your username contains spaces. Please try again: ")
            elif not sNewUser1.isalnum():
                print("Your username contains a special character. "
                    "Please try again: ")
            else:
                break

        global sNewPass1
        while True:
            sNewPass1 = input("\n\nPlease enter a new password.\n"
                            "It should be at least 6 characters long\n"
                            "with at least one uppercase letter,\n"
                            "one lowercase letter, one special character"
                            "and one number: \n\n")

            if len(sNewPass1) < 6:
                print("\nYour password is too short. Please try again: ")
            elif not any(lower.islower() for lower in sNewPass1):
                print("\nYour password does not contain lowercase letters. "
                    "Please try again: ")
            elif not any(upper.isupper() for upper in sNewPass1):
                print("\nYour password does not contain uppercase letters. "
                    "Please try again: ")
            elif not any(digit.isdigit() for digit in sNewPass1):
                print("\nYour password does not contain a number. "
                    "Please try again: ")
            elif all(char.isalnum() for char in sNewPass1):
                print("\nYour password does not contain a special character. "
                    "Please try again: ")
            elif " " in sNewPass1:
                print("\nYour password contains whitespaces. "
                    "Please try again: ")
            else:
                break

    def name_selection():
        print("Account created sucessfully!")
        global sName1
        sName1 = input("Please enter your name:\n")

    def user_login():
        while True:
            sUserLogin = input("Please enter your username:\n")
            if sUserLogin == sNewUser1:
                break
            else:
                print("Wrong username please try again:\n")
        while True:
            sUserPass = input("Please enter your password:\n")
            if sUserPass == sNewPass1:
                print("\nWelcome: ", sName1)
                break

    # 依次调用登录流程函数
    admin_login()
    new_account()
    name_selection()
    user_login()

修复说明

  1. 菜单函数返回选择结果:修改menu()函数返回用户选择值,后续通过判断该值决定是否执行登录流程。
  2. 条件控制后续执行:将所有登录相关的函数定义和调用放在if user_choice == 1:代码块中,仅当用户选择登录时才触发。
  3. 修复异常处理逻辑:用continue替代递归调用,回到循环开头重新获取输入,避免栈溢出。
  4. 简化判断逻辑:将is False类判断改为更简洁的not,提升代码可读性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 13:01:12