【问题标题】:Looping the function循环函数
【发布时间】:2016-06-07 17:32:49
【问题描述】:

我下面有这个功能,我在某处做错了。

def quantityFunction(product):
    valid = False
    while True:
        if product is not None:
            quantity = input("Please enter the amount of this item you would like to purchase: ")
            for i in quantity:
                try:
                    int(i)
                    return int(quantity)
                    valid = True
                except ValueError:
                    print("We didn't recognise that number. Please try again.")
                    #If I get here, I want to loop back to the start of this function
                    return True

        return False

为了运行,从程序的主要部分调用该函数,如下所示:quantity = quantityFunction(product)

代码底部的return False与if product为None有关,这是在另一个函数中的一些代码之后需要的,但必须进入这个函数。

如果用户输入的数量是一个数字,一切正常。如果是其他内容,则会打印值错误,您可以输入另一个输入。如果你输入另一个字母等,它会再次重复,如果你输入一个数字,它会接受它。

但是,它不会返回您在字母后面输入的数字。它只返回 0。

我怀疑这与我重复代码的方式有关,即如果遇到值错误,代码应该循环回到函数的开头。

有什么想法吗?

【问题讨论】:

  • 你在 except 块中有一个 return 语句。只需打印错误消息,它应该可以正常工作。
  • 为什么要定义valid?它从未使用过。为什么是for循环?为什么不尝试立即将数量转换为 int?
  • 现在我已经从 except 块中取出了 return,函数没有循环,我怎样才能让它这样做? @SilentMonk

标签: python function loops


【解决方案1】:

你说:

如果遇到值错误,代码应该循环回到函数的开头。

那么你不应该使用return语句,否则函数将终止,返回TrueFalse

【讨论】:

  • 好的,我已经从 except 块中取出了 return。现在函数不循环了,我怎样才能让它这样做呢? @heltonbiker
  • 我更正了答案,您有两个退货,一个是异常,另一个是常规流程。删除两者
  • 我认为你对 return 和循环有一个错误的想法。您返回TrueFalse 的意图是什么?
【解决方案2】:

几个问题:

1) return 语句将控制权返回给调用函数。

2) 你正在循环输入,这是错误的。

3) valid=True 根本不执行。

def quantityFunction(product):
    valid = False
    while True:
        if product is not None:
            quantity = raw_input("Please enter the amount of this item you would like to purchase: ")
            try:
                    return int(quantity)
                    #valid = True (since it is never run)
            except ValueError:
                    print("We didn't recognise that number. Please try again.")
                    #If I get here, I want to loop back to the start of this function
                    #return True 
        return False

quantityFunction("val")

注意:在 Python 2.7 的情况下使用raw_input(),在 3.x 的情况下使用input()

【讨论】:

    【解决方案3】:

    试试这个(也包括一些格式,但功能应该相同):

    def determine_quantity(product):  # descriptive function name
        if not product:  # avoiding nesting
             return False
        while True:
            quantity = input("Please enter the amount of this item you would like to purchase: ")
            try:
                return int(quantity)  # try to convert quantity straight away
            except ValueError:
                print("We didn't recognise that number. Please try again.")
                # nothing here means we simply continue in the while loop
    

    理想情况下,您会取出产品。一个函数应该做的越少越好,这个检查在其他地方会更好。

    def determine_quantity():
        while True:
            quantity = input("Please enter the amount of this item you would like to purchase: ")
            try:
                return int(quantity)
            except ValueError:
                print("We didn't recognise that number. Please try again.")
    

    【讨论】:

      【解决方案4】:

      首先,让我们解决代码。简单地说,您需要一个循环直到用户输入合法数量的函数。

      product 对功能没有多大作用;在调用程序中检查它,而不是在这里。让函数有一个目的:获取有效数量。

      让我们从“循环直到好的输入”的标准配方开始工作。很简单,它看起来像:

      Get first input
      Until input is valid
      ... print warning message and get a new value.
      

      在代码中,它看起来像这样。

      def get_quantity():
          quantity_str = input("Please enter the amount of this item you would like to purchase: ")
      
          while not quantity_str.isdigit():
              print("We didn't recognise that number. Please try again.")
              quantity_str = input("Please enter the amount of this item you would like to purchase: ")
      
          return quantity
      

      至于编码练习……

      渐进式开发:编写几行代码以将一个功能添加到您拥有的东西中。调试那个。在添加更多之前让它工作。

      了解您的语言功能。在您发布的代码中,您滥用了 forinreturn 和函数调用。

      了解如何解决简单问题。 try/except 是一个比简单的 isdigit 更难处理的概念。

      【讨论】:

        【解决方案5】:

        你应该试试这个..

        def quantityFunction(product):
            valid = False
            while True:
               if product is not None:
                  quantity = raw_input("Please enter the amount of this item you would like to purchase: ")
        
                  if quantity.isdigit():
                     return int(quantity)
                     valid = True
                  else:
                     print("We didn't recognise that number. Please try again.")
                     continue
        
               return False
        
        quantity = quantityFunction("myproduct")
        

        【讨论】:

          猜你喜欢
          • 2018-08-06
          • 1970-01-01
          • 2015-07-13
          • 2019-08-28
          • 2021-12-03
          • 2016-01-04
          • 2021-01-14
          • 1970-01-01
          相关资源
          最近更新 更多