Skip to main content
 首页 » 编程设计

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

2025年04月02日33bhlsheji

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

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.") 

有什么方法可以使您可以用“退出”回答任何问题,并且它会关闭用户管理器,而无需为每个单独的问题添加 if 语句?任何帮助将不胜感激!谢谢!

请您参考如下方法:

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

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

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

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