我在下面有这个功能,我在某处做了某些错误。循环功能
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)
返回的代码的底部假是,如果产品是无,这是做需要在另一个函数中的一些代码,但不得不在这个功能。
如果用户输入数量是一个数字,所有工作正常。如果是其他内容,则会打印“值错误”,您可以输入另一个输入。如果你再写一封信等,它会再次重复,如果你输入一个数字,它会接受它。
但是,它不会返回您在字母后输入的数字。它只返回0.
我怀疑这是关于如何重复代码,即代码应该循环回到函数的开始,如果它击中值错误。
任何想法?
你在return块中有return语句。只需打印错误消息,它应该可以正常工作。 – SilentMonk
为什么你定义'valid'?它从未使用过。为什么是for循环?为什么不尝试将数量直接转换为int? – Ben
现在我已经把除了块以外的函数返回,函数不会循环,我怎么能这样做呢? @SilentMonk –