数の階乗を見つけるPythonプログラム

Python

数値の階乗は、1からその数値までのすべての整数の積です。

たとえば、6の階乗は 1*2*3*4*5*6 = 720。 階乗は負の数に対して定義されておらず、ゼロの階乗は1であり、 0! = 1

ソースコード

# Python program to find the factorial of a number provided by the user.

# change the value for a different result
num = 7

# To take input from the user
#num = int(input("Enter a number: "))

factorial = 1

# check if the number is negative, positive or zero
if num < 0:
   print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
   print("The factorial of 0 is 1")
else:
   for i in range(1,num + 1):
       factorial = factorial*i
   print("The factorial of",num,"is",factorial)

出力

The factorial of 7 is 5040

注意: 別の番号でプログラムをテストするには、の値を変更します。 num

ここでは、階乗が見つかる番号がに格納されます num、を使用して、数値が負、ゼロ、または正であるかどうかを確認します if...elif...else ステートメント。 数値が正の場合、 for ループと range() 階乗を計算する関数。



Hope this helps!

Source link

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です