Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/313.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 循环函数_Python_Function_Loops - Fatal编程技术网

Python 循环函数

Python 循环函数,python,function,loops,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:

我在下面有一个函数,我在某个地方做错了什么

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与product是否为None有关,这是在另一个函数中的一段代码之后需要的,但必须在这个函数中执行

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

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

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

有什么想法吗?

你说:

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

然后,您不应该使用
return
语句,否则函数将终止,返回
True
False
您应该尝试此操作

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")
少数问题:

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

注意:在Python2.7中使用
raw_input()
,在3.x中使用
input()
,首先,让我们讨论一下代码。简单地说,您需要一个循环函数,直到用户输入合法数量

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

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

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

更难处理的概念。试试这个(也包括一些格式,但功能应该相同):

理想情况下,你应该把产品拿出来。函数应该尽可能少地执行,而这种检查最好在其他地方进行

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

在except块中有一个return语句。只需打印错误消息,它就可以正常工作。为什么要定义
valid
?从来没用过。为什么是for循环?为什么不直接尝试将数量转换为int呢?现在我已经将返回从except块中取出,函数不循环,我如何使它这样做@SilentMonkOkay,我已经把回程票带出了街区。现在函数不循环了,我怎样才能让它循环呢@heltonbikerI更正了答案,您有两个返回,一个为异常,另一个为常规流。删除两者我认为你对返回和循环有错误的想法。返回
True
False
的目的是什么?
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.")