2017-06-20 11 views
0

このPython関数では、ユーザー入力を非整数値(小数点以下の桁数など)を指定しないように処理し、それ以外の場合は例外を処理します。Python:階乗法への入力の制御

# a function that takes an integer and returns its factorial 
def factorial(x): 
    try: 
     if x == 0: 
      return (0) 
     else: 
      pro = 1 
      for i in range(1, x + 1): 
       pro *= i 
    except(ValueError, TypeError): 
     # this part of the code is supposed to handle exception for invalid input5 
     print("an error happened") 
    return (pro) 


# calling the function with validated input 
# warning!!! this program my take longer time as your input get larger 
num = int(input("Enter a positive integer:")) 
if num >= 0: 
    print("\n Factorial of " + str(num) + " = " + str(factorial(num))) 
else: 
    print("Factorial is operated only on positive number"); 
+2

0の階乗は1であり、コードでは0ではありません。そうでなければ、正確にあなたの質問は何ですか? –

答えて

1

assertステートメントをここで使用できます。

num = int(input("Enter a positive integer:")) 

assert isinstance(num, int) and num >= 0, 'Factorial is operated only on positive number' 

アサーションがfalseの場合、AssertionErrorが提供されたメッセージにスローされます。さらに、コードのどこにでもこれをアサートすることができます。あなたの関数内でも、try/exceptブロックの必要性を排除します。


デコレータで問題を解決する方法は次のとおりです。デコレータは、階乗が計算される前にアサーションを実行します。

@checknum 
def factorial(x):  
    if x == 0: 
     return 1 # changing this to 1, not 0 
    else: 
     pro = 1 
     for i in range(1, x + 1): 
      pro *= i 

    return pro 

def checknum(function): 
    def wrapper(x): 
     assert isinstance(x, int) and x >= 0, 'Factorial is operated only on positive number' 
     return function(x) 
    return wrapper 
+0

コード全体をエディタにコピーしても機能しませんでした。 –

+0

@MinilikTesfayeあなたは具体的になりますか?どのようなエラーがありましたか?構文エラーかランタイムですか? –

+0

私はあなたがまだ階乗(x)でメソッドを呼び出すことに言及する必要があります。デコレータはバックグラウンドでその魔法を働かせます。 –