循环功能

时间:2016-06-07 17:32:49

标签: python function loops

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

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)

代码底部的返回False是if产品是否为None,这是在另一个函数中的一些代码之后需要但是必须使用此函数。

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

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

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

任何想法?

5 个答案:

答案 0 :(得分:3)

你说:

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

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

答案 1 :(得分:3)

几个问题:

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()

答案 2 :(得分:1)

你应该试试这个..

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

答案 3 :(得分:1)

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

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

让我们从标准配方开始工作,然后循环直到良好输入"。非常简单,它看起来像:

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

至于编码实践......

逐步开发:编写几行代码,将一个功能添加到您拥有的内容中。调试那个。在添加更多内容之前让它工作。

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

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

答案 4 :(得分:1)

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

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