如何在Python中编写一个永远在线的“退出”选项?

时间:2016-03-21 03:58:41

标签: python list if-statement keyword exit

我正在学习Python并且正在编写一个基本的“用户配置文件管理器”。此程序将能够向包含已保存用户帐户的现有文件添加,编辑或删除用户帐户。我已经设置好了,所以使用该程序的人会经历一系列问题来完成添加,编辑或删除(整个过程都是基于文本的)。我想知道是否有一种方法可以让每个问题都听一个'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.")

我有什么方法可以做到这一点,你可以用“退出”回答任何问题,它会关闭用户管理器,而不会为每个问题添加 if 语句?任何帮助将不胜感激!谢谢!

1 个答案:

答案 0 :(得分:1)

function getSanitizedProduct(ProductData, SellerData, SubscriptionId){ var productId = SellerData.product.id; var versionId = {'version': SubscriptionId}; return ProductData.getWhitelistedData(productId, versionId).then(function(product){ // plain() is a Restangular method that strips unnecessary properties return product.plain(); }); } 函数包装到您自己的函数中,并将条件检查放在那里:

input()

^然后调用此函数而不是def custom_input(question): answer = input(question).lower() if answer == 'quit': sys.exit() # or whatever you want to do return answer 函数

上面 - 我还建议您使用数据库来更轻松地管理用户记录而不是文本文件,并对密码进行哈希处理,这样它们就不会存储为纯文本。