如何在 Python 中写一个永远在线的 "Quit" 选项?

How can I write an always-on "Quit" option in Python?

我正在学习 Python 并且正在编写一个基本的 "user profile manager." 该程序将能够添加、编辑或删除用户帐户 to/from 一个包含已保存用户帐户的现有文件.我已经设置好它,以便使用该程序的人通过一系列问题来完成添加、编辑或删除(整个过程都是基于文本的)。我想知道是否有一种方法可以让每个问题都监听 'quit' 关键字,这将关闭用户管理器程序,而不必输入 if 语句对于每个单独的问题 'quit'。这是 删除用户 能力的代码:

action1 = input("Currently saved users:\n" +
                    # userList is a dictionary containing saved users
                    str(userList.keys()) +
                    "\nEnter the name of the profile you would like to delete.\n"
                    ).lower()

    # Prevent the built in Admin and Guest users from being modified
    while action1 == "guest" or action1 == "admin":
        print("Sorry, this profile cannot be modified. Please try again.")
        action1 = input("Enter the name of the profile you would like to delete.\n").lower()

    # Require the active user's password to complete the deletion process (if active user has a password)
    if user.password != None:
        delpass = input("Please enter your password to complete this action:\n")
        while delpass != user.password:
            delpass = input("Incorrect password for %s. Please try again:\n" %user.username)
    else:
        pass

    # Make sure one more time that the active user is sure about deletion
    action2 = input("Are you sure you want to delete this user profile?\n").lower()

    # Delete the selected user profile (which is action1)
    if action2 == "yes":
        del userList[action1]
        print("User " + action1 + " has been deleted from saved users.")
    else:
        print("Deletion of user " + action1 + " has been cancelled.")

有什么方法可以让你用 'quit' 回答任何问题,它会关闭用户管理器,而不添加 if每个问题的陈述?任何帮助将不胜感激!谢谢!

input() 函数包装到您自己的函数中,并将条件检查放在那里:

def custom_input(question):
    answer = input(question).lower()
    if answer == 'quit':
        sys.exit() # or whatever you want to do
    return answer

^ 然后调用此函数而不是 input() 函数

除此之外 - 我还建议您使用数据库而不是文本文件来更轻松地管理用户记录,并散列您的密码,因此它们不会以纯文本形式存储。