2016-06-11 66 views
1

我的代碼如下檢查輸入(數量)是一個數字。如果第一次是數字,它會返回數字。但是,如果您要輸入一個字母,然後當函數循環輸入一個數字時,將返回「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 

我正在循環功能嗎?

+1

你可能也想閱讀這個答案 - http://stackoverflow.com/a/23294659/471899 – Alik

+1

你必須返回函數的值,即。 'return quantityFunction()'但仍然正確的方法是@Alik發佈的方法。 – Selcuk

+1

不應該是:'爲我在範圍(數量):'如果數量實際上是一個數字? – shiva

回答

3

你的功能實際上是不正確的,你正在使用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()。否則最終不會返回任何內容。這也解釋了你爲什麼在你第一次輸入號碼時輸入號碼的問題,但不能在之後輸入號碼。

+0

謝謝!那工作 –

+1

@NathanShoesmith,我更新了答案,這應該是另一種實現你想要的方式。 – MaThMaX

+0

@NathanShoesmith,我添加了遞歸函數,我想這可能會解釋你的問題,即當你第一次輸入數字時,你可以返回它,但之後不會。 – MaThMaX