【问题标题】:How to return another return?如何退货?
【发布时间】:2019-07-01 22:58:26
【问题描述】:

我希望在我的 Python 程序中使用函数以使其更简洁、更高效。在我的函数中,我根据用户的选择返回 true 或 false。尽管在他们输入错误/无效响应的情况下,我想以不问更多问题的方式返回。

编辑:

更具描述性;我想重新创建这个:

def askquestion(question):
    response = input(question, "Enter T or F")
    if response == "T":
        return True
    elif response == "F":
        return False
    else:
        return None 

def askmultiple():
    questionOne = askquestion("Do you fruits?")
    if questionOne == None:
        return # Exit the function, not asking more questions

    questionTwo = askquestion("Do you Apples?")
    if questionTwo == None:
        return # Exit the function, not asking more questions

我想以后检查是否是None,然后直接返回。

【问题讨论】:

  • 能否请您出示您目前拥有的代码,以便我们了解您在做什么
  • “我想退货”这没有意义。 return 是语句的一部分,它不是对象,因此无法返回。你不妨问“我如何返回if
  • 这听起来像是你想要Asking the user for input until they give a valid response 所要求的。我没有立即将其标记为重复的唯一原因是您的问题太模糊,无法确定它是重复的。

标签: python return


【解决方案1】:

当您不在函数末尾创建等于唯一 return 的 return 语句并且这两个等于 return None 调用时。

所以你可以像这样组织你的代码:

if returned_value is None:
    # do something a
elif returned_value is False:
    # do something else
else:  # value is True
    # do something b

【讨论】:

    【解决方案2】:

    您可以尝试使用 while 循环来确保用户输入正确的输入。 例如:

    while not response.isdigit():
         response =  input("That was not a number try again")
    

    在这种情况下,当用户输入时,“响应”不是一个数字,python 控制台会不断要求响应。对于基本模板,

    while not (what you want):
        (ask for input again)
    

    我希望这对你有帮助。 :)

    【讨论】:

    • 这回答了你的问题吗?
    【解决方案3】:

    使用异常流。

    def ask_question(prompt):
        """Asks a question, translating 'T' to True and 'F' to False"""
        response = input(prompt)
    
        table = {'T': True, 'F': False}
        return table[response.upper()]  # this allows `t` and `f` as valid answers, too.
    
    def ask_multiple():
        questions = [
            "Do you fruits?",
            "Do you apples?",
            # and etc....
        ]
    
        try:
            for prompt in questions:
                result = ask_question(prompt)
        except KeyError as e:
            pass  # this is what happens when the user enters an incorrect response
    

    因为如果response.upper() 既不是'T' 也不是'F'table[response.upper()] 将引发KeyError,您可以在下面抓住它并使用该流程将您移出循环。


    另一种选择是编写一个强制用户正确回答的验证器。

    def ask_question(prompt):
        while True:
            response = input(prompt)
            if response.upper() in ['T', 'F']:
                break
        return True if response.upper() == 'T' else False
    

    【讨论】:

    • 这项工作是否为您工作,如果有,请勾选它。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-17
    • 2011-08-15
    • 2023-03-12
    • 1970-01-01
    • 2013-01-05
    • 2013-08-04
    • 1970-01-01
    相关资源
    最近更新 更多