2016-06-11 3 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() 

注意したいのは、ですあなたが数字を入力すると最終的に返されるのは、elsereturn quantityFunction()です。さもなければ最終的に何も返されません。これはまた、最初にあなたがそれを返すことができるが、それを返すことができないときに、なぜあなたが入力したのかというあなたの質問を説明する。

+0

ありがとう!それは、 –

+1

@ NathanShoesmithさん、私は答えを更新しました。これはあなたが望むものを達成する別の方法でなければなりません。 – MaThMaX

+0

@NathanShoesmith、私はあなたの質問を説明してくれる 'recursion'関数を追加しました。最初に数値を入力したときに返すことができましたが、その後は返すことはできません。 – MaThMaX

関連する問題