Python 变量的循环和返回不正确

Python 变量的循环和返回不正确,python,Python,我下面的代码正在检查输入(数量)是否为数字。如果是第一次使用数字,则返回数字fine。但是,如果要输入一个字母,然后当函数循环输入一个数字时,返回的是“0”,而不是您输入的数字 def quantityFunction(): valid = False while True: quantity = input("Please enter the amount of this item you would like to purchase: ")

我下面的代码正在检查输入(数量)是否为数字。如果是第一次使用数字,则返回数字fine。但是,如果要输入一个字母,然后当函数循环输入一个数字时,返回的是“0”,而不是您输入的数字

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

我是否循环函数不正确?

您的函数实际上不正确,您使用的是
,而
递归函数一起循环,在这种情况下,这是不必要的

While,您可以尝试以下代码,这是基于您的函数的一点修改,但只使用
While
循环

def quantityFunction():
    valid = False
    while not valid:
        quantity = input("Please enter the amount of this item you would like to purchase: ")
        for i in quantity:
            try:
                int(i)
                return int(quantity)
            except ValueError:
                print("We didn't recognise that number. Please try again.")
                valid = False
                break

不过,如果您希望在循环时使用
的话,实际上您可以用一种更简单的方法来实现这一点:

def quantityFunction():
    while True:
        quantity = input("Please enter the amount of this item you would like to purchase: ")
        if quantity.isdigit():
            return int(quantity)
        else:
            print("We didn't recognise that number. Please try again.")
如果确实要使用递归函数
,请尝试以下操作:

def quantityFunction1():
    quantity = input("Please enter the amount of this item you would like to purchase: ")
    if quantity.isdigit():
        return int(quantity)
    else:
        print("We didn't recognise that number. Please try again.")
        return quantityFunction()

请注意如果您希望在键入数字时最终返回值,则需要使用
中的
return quantityFunction()
。否则最终什么也不会归还。这也解释了为什么您在第一次输入数字时可以返回,但之后不能返回。

您可能还想阅读此答案-您必须返回函数的值,即
return quantityFunction()
,但正确的方法仍然是@Alik发布的方法。它不应该是:
用于范围内的i(数量):
如果数量实际上是一个数字?如果输入了一个数字,你是想停止循环还是只想继续?@NathanShoesmith,我更新了答案,这应该是实现你想要的另一种方式。@NathanShoesmith,我添加了
递归
函数,我想这可以解释您的问题,当您第一次输入一个数字时,您可以返回它,但之后不能返回。