你的功能實際上是不正確的,你正在使用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