2016-06-11 102 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