In: Computer Science
The factorial of a nonnegative integer n is written n!
(Pronounced “n factorial”) and is defined as follows: n! = n.(n-1).
(n-2).……...1 (for values of n greater than 1) n!=1 (for n = 0 or
1)
For instance, 5! = 5.4.3.2.1 which is 120.
Write a Python program that reads a nonnegative integer n and
calculates and prints its factorial. Your program should display a
suitable error message if n entered as a negative integer.
Figure 6. Exercise
6 Sample Run for
n = 0, -8
and 5.
PYTHON CODE
#function to find fact
def fact(n):
f = 1;
# if number is 0 or 1 than fact will be 1
if n==0 or n==1:
return 1
#else it will be mul of all number from 1 till n
else:
i=1
while i<=n:
f=f*i
i+=1
return f
n = int(input("Enter a number : "))
#if number is negative
if(n<0):
print("Factorial of negative number does not exist.")
#if input is non negative number
else:
print("Factorial of " + str(n) + " is : " + str(fact(n)))