你的功能实际上是不正确的,你正在使用while
循环连同recursion function
,在这种情况下这是不必要的。虽然,您可以尝试以下代码,该代码根据您的功能稍微修改,但只使用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
尽管实际上你可以在一个更简单的方式做到了这一点,如果你想使用while loop
:
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.")
如果你真的想用recursive function
,尝试以下操作:
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()
请注意如果你想要VA当你输入一个数字时,最终返回,你需要在else
中使用return quantityFunction()
。否则最终不会返回任何内容。这也解释了你为什么在你第一次输入号码时输入号码的问题,但不能在之后输入号码。
你可能也想阅读这个答案 - http://stackoverflow.com/a/23294659/471899 – Alik
你必须返回函数的值,即。 'return quantityFunction()'但仍然正确的方法是@Alik发布的方法。 – Selcuk
不应该是:'为我在范围(数量):'如果数量实际上是一个数字? – shiva